单击角度4中的按钮时动态添加输入

时间:2017-11-21 11:35:52

标签: javascript forms angular

我会创建一个可以动态添加输入的表单 我在角度2中找到了question关于同样问题的问题,但是我无法使其在我的例子中工作

这是我的组件 ts 文件:

export class AjoutProjetComponent implements OnInit {
    isLinear = false;
    firstFormGroup: FormGroup;
    secondFormGroup: FormGroup;

    constructor(private _formBuilder: FormBuilder) {}

    ngOnInit() {
        this.secondFormGroup = this._formBuilder.group({
            pers: [this._formBuilder.array([this.createItem()])]
        });
    }
    createItem(): FormGroup {
        return this._formBuilder.group({
            name: ['', Validators.required]
            poste: ['', Validators.required],

        });
    }
    addItem(): void {
        const control = < FormArray > this.secondFormGroup.controls['pers'];
        control.push(this.createItem());
    }

}

然后是HTML文件

<mat-step [stepControl]="secondFormGroup">
    <form [formGroup]="secondFormGroup">
        <ng-template matStepLabel>Constituez votre équipe</ng-template>
        <div formArrayName="pers">
            <mat-form-field *ngFor="let control of secondFormGroup.controls.pers.controls; let i= index">
                <input matInput placeholder="Nom collaborateur" formControlName="name" required>
            </mat-form-field>

        </div>
    </form>
</mat-step>
        <div>{{secondFormGroup.value | json}}</div>

当我点击我最喜欢的图标时,我收到此错误:

ERROR TypeError: control.push is not a function at AjoutProjetComponent.addItem

如何添加动态输入?

更新 我更新了我的html代码,以便我可以打印两个输入,但是当我运行我的代码时,我现在收到此错误

ERROR Error: Cannot find control with path: 'pers -> name'

1 个答案:

答案 0 :(得分:1)

您没有正确声明FormArray。您只使用数组初始化简单的FormControls,而不是FormGroupsFormControls,更改为:

this.secondFormGroup = this._formBuilder.group({
        pers: this._formBuilder.array([this.createItem()]) // remove opening and closing brackets
    });

要查看动态添加到html的输入,您需要使用ngFor循环。我认为你有点误解了formArrayName的用法,FormArrays只会在模板中添加上下文以与<ng-container formArrayName="pers"> <input placeholder="Address" *ngFor="let control of secondFormGroup.controls.pers.controls" [formControl]="control.controls.name" required /> </ng-container> 一起使用。试试这个:

FormArrayName

详细了解import heapq manhattan = {'path1_a': {'path2_a': 1, 'path2_b': 5}, 'path1_b': {'path2_c': 3, 'path2_d': 7}, 'path1_c': {'path2_e': 4, 'path2_f': 9}} print heapq.nsmallest(3, ((path1, path2, value) for path1, path2s in manhattan.items() for path2, value in path2s.items()), key=lambda (path1, path2, value): value) 指令here