Angular 5 - 反应形式 - 有没有办法使用变量来修补值?

dan*_*nda 4 javascript typescript angular angular-reactive-forms

我有一个包含许多字段的表单组:

    this.addressForm = this.formBuilder.group({
        line1: ['', Validators.required],
        line2: '',
        line3: '',
        line4: '',
        line5: '',
        line6: '',
        line7: '',
        line8: '',
    });
Run Code Online (Sandbox Code Playgroud)

在我的 html 中,每个 formControl 都有一个表单字段,附近有一个按钮可以清除该表单控件。

                <mat-form-field>
                    <mat-label>line 1</mat-label>
                    <input matInput formControlName="line1" type="text">
                    <button type="button" (click)="clearLine('line1')">
                    </button>
                </mat-form-field>
Run Code Online (Sandbox Code Playgroud)

如何编写一个通用方法来获取表单控件的名称并清除它?

我试试这个——

clearLine(line) {
    this.addressForm.patchValue({line: ''});
}
Run Code Online (Sandbox Code Playgroud)

但这不起作用,因为它搜索了 formControl 名称“line”。

有没有办法在不执行许多“if”条件的情况下做到这一点?

Fra*_*lli 9

尝试这个

clearLine(line) {
    this.addressForm.patchValue({[line]: ''}); // added []
}
Run Code Online (Sandbox Code Playgroud)

  • 没有问题!...添加括号将使访问替代变量名称。就像 object['hey'] 等于 object.hey。快乐编码! (2认同)