I am developing Job form where user can enter his hobbies in the Job Form. I have applied required validation on hobbyName formcontrol, but how can I validate hobby name which should be unique if there is more than one hobby.
Below is my ts code
import { Component,OnInit } from '@angular/core'; import { FormGroup,FormArray,FormBuilder,Validators } from "@angular/forms" @Component({ selector: 'my-app', templateUrl: './app.component.html', styleUrls: [ './app.component.css' ] }) export class AppComponent implements OnInit { jobForm:FormGroup constructor(private jobfb:FormBuilder){} ngOnInit(){ this.jobForm = this.jobfb.group({ hobbies:this.jobfb.array([ this.createHobbyFormGroup() ]) }) } addHobby(){ let hobbies = this.jobForm.controls.hobbies as FormArray; hobbies.push(this.createHobbyFormGroup()); } createHobbyFormGroup(){ return this.jobfb.group({ hobbyName:['',Validators.required] }); } } below is my Html code
<button (click)="addHobby()">Add Hobby</button> <table> <tr [formGroup]="hobbyFG" *ngFor="let hobbyFG of jobForm.controls.hobbies.controls;"> <input formControlName="hobbyName"/> </tr> </table> <button [disabled]="!jobForm.valid">Submit</button> whenever user click on add button, at that time new FormGroup will be added in the FormArray.
I am not able to figure out how can I validate the hobby name, which should be unique?
Please guide.