5

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?

1 Answer 1

19

try this

clearLine(line) {
    this.addressForm.patchValue({[line]: ''}); // added []
}
Sign up to request clarification or add additional context in comments.

1 Comment

no prob!... adding brackets will make the access substitute variables names. Just like object['hey'] equals object.hey. Happy coding!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.