I am using angular6 reactive form with form builder and form array. I am facing problem with duplicate subject entry from drop down in form array. How to validate to avoid duplicate entry in from array.
I have a subject list with drop down. When i click on add button then a subject array will add. If i add similar subject it also be added. But i want to avoid duplicate subject entry. When i entry duplicate subject then a validation message will show and save button will disable.
ts code
olevelSubForm = this.fb.group({ olevelSubArray: this.fb.array([ ]) }); olevelSubjectList: any = [ 'Geography','Mathematics', 'Physics','Chemistry']; constructor(private fb: FormBuilder) {} ngOnInit() { this.addItemOlevel(); } // olevel createOlevelSub(): FormGroup { return this.fb.group( { olevelSubject: new FormControl('', Validators.compose( [ Validators.required ] )), }); } addItemOlevel() { const control = <FormArray>this.olevelSubForm.controls.olevelSubArray; control.push(this.createOlevelSub()); } saveData() { console.log('saved') } html code
<form [formGroup]="olevelSubForm" > <div formArrayName="olevelSubArray"> <table> <thead> <tr style="font-size: 15px;"> <th>Subject</th> </tr> </thead> <tbody> <tr *ngFor="let item of olevelSubForm.get('olevelSubArray').controls; let i = index;" [formGroupName]="i"> <td> <select formControlName="olevelSubject"> <option *ngFor="let olevelSub of olevelSubjectList" [value]="olevelSub">{{ olevelSub }}</option> </select> </td> <td> <button style="float: right" [disabled]="olevelSubForm.invalid"(click)="addItemOlevel()"> Add </button> </td> </tr> </tbody> </table> <button [disabled]="olevelSubForm.invalid"(click)=saveData()>Save</button> <pre> {{ olevelSubForm.value | json }} </pre> </div>