最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular 5 - reactive form- is there a way to patch value using a variable? - Stack Overflow

programmeradmin5浏览0评论

I have a form group with many fields :

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

In my html I have a form field to each formControl and a button near it that clears that form control.

                <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>

How Can I write a generic methods that gets the name of the form control and clears it?

I tries this-

clearLine(line) {
    this.addressForm.patchValue({line: ''});
}

but that did not work, because it searched for a formControl name "line".

Is there any way to do this without execute many "if" conditions?

I have a form group with many fields :

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

In my html I have a form field to each formControl and a button near it that clears that form control.

                <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>

How Can I write a generic methods that gets the name of the form control and clears it?

I tries this-

clearLine(line) {
    this.addressForm.patchValue({line: ''});
}

but that did not work, because it searched for a formControl name "line".

Is there any way to do this without execute many "if" conditions?

Share Improve this question edited Jun 12, 2019 at 8:19 danda asked Jun 12, 2019 at 8:17 dandadanda 58314 silver badges32 bronze badges
Add a ment  | 

1 Answer 1

Reset to default 19

try this

clearLine(line) {
    this.addressForm.patchValue({[line]: ''}); // added []
}
发布评论

评论列表(0)

  1. 暂无评论