I have requirement where I want to implement logic to assign object array data to input control dynamically and based on updation I want to update my array as well as I want to fire validation to check whether entered names/data in control having duplicate entries. For validation I have used ReactiveForm module. But I am facing below 2 issues –
- How I create the same array structure so that on successful validation I can directly pass the updated structure to api?
- How I assign id from array object to formControlName, currently I am assigning it with loop index.
plunkar reference here - https://plnkr.co/edit/RSBpT0sFSI1GDCp6K7VR?p=preview
Component:
@Component({
selector: 'my-app',
template: `
<div>
<h3> Custom Group Validation</h3>
<form [formGroup]="myForm">
<div class="left">
names: <br>
<div formArrayName="names">
<div *ngFor="let item of namesArray.controls; let i = index">
<input type="text" [formControlName]="i">
<button (click)="removeAt(i)">X</button><br>
</div>
</div>
<div *ngIf="namesArray.hasError('duplicate')">
duplicate entries
</div>
<pre>Array value: <br>{{namesArray.value | json}}</pre>
</div>
</form>
</div>
`
})
Class (abstract):
namesArray:FormArray = new FormArray([], this.customGroupValidation );
dataArray: { custId: number, customerName: string }[] = [
{ custId: 101, customerName: 'John' },
{ custId: 102, customerName: 'Mike' },
{ custId: 103, customerName: 'Julia' }];
ngOnInit():void{
for(let ele of this.dataArray){
this.namesArray.push(
new FormControl(ele.customerName)
);
}
}
Any Help Appreciated!