1

I am new to angular and currently using angular 5 i want to add check box and drop down list on click event() using Reactive form control. Please suggest a solution.

1 Answer 1

2

Your html template should look something like below:

<div formArrayName="items" *ngFor="let item of items.controls; let i=index">
    <div [formGroupName]="i" class="well">
        <input type="checkbox" formControlName="isChecked" />
    </div>
    <div *ngIf="isChecked.invalid && (isChecked.dirty || isChecked.touched)"
          class="alert alert-danger">
        <div *ngIf="isChecked.errors.required">
            Checkbox is required.
        </div>
    </div>
</div>
<button type="button" (click)="addItem()">Add Item</button>

Component file should contain a FormGroup with a FormArray called items defined in it.

 this.formGroup = this.formBuilder.group({
          items: this.formBuilder.array([])
 })

The below code is a getter property for easy access.

get items(): FormArray {
    return this.formGroup.get('items') as FormArray;
}

To add a checkbox on click.

private addItem(): void {
    this.items.push(this.buildItem());
}

private buildItem(): FormGroup {
    return this.formBuilder.group({
          id: [''],
          isChecked: [false, Validators.required],
    });
}

Note: I haven't tried it so correct the syntax as necessary.

Sign up to request clarification or add additional context in comments.

7 Comments

there are only one correction *ngFor="let item of items; but i also need to implement validation and two way binding .how can i do this
Two way binding? This is not regular forms, this is Reactive forms. That is what you asked for in your question. Seems like you are getting confused with ngmodel in forms and reactive forms. In Reactive Forms, it is two way binding by default. You don't have to specify it again. You can read more about it here: angular.io/guide/reactive-forms
You can add validation to it depending on what you want to validate. Can you be more specific?
@SunilRai Can you accept the answer, if it worked for you?
@Sandeep I need required field validation and I also want to select check box when i click first time on add button. Please suggest a solution
|

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.