Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 312
danda Avatar asked Jun 12 '19 08:06

danda


1 Answers

try this

clearLine(line) {
    this.addressForm.patchValue({[line]: ''}); // added []
}
like image 182
Francisco Santorelli Avatar answered Oct 22 '22 03:10

Francisco Santorelli