From a parent component, I am passing the form array to the child component in this way.
<form [formGroup]="myForm" (ngSubmit)="onSubmit()">
<hello [myForm]="myForm"></hello>
</form>
In the parent component .ts I have fetched the data from API and bind the result to the form array.
Form array is defined as:
this.myForm = this.fb.group({
frequency: [2, Validators.required],
memberid: this.fb.array([]),
});
In the ngOnInit() i have called the the function callApi():
async callApi() {
const fTitle = this.myForm.controls.memberid as FormArray;
const response = await fetch(this.url);
const json = await response.json();
let arr = [];
json.map((item) => arr.push(item.id));
arr.forEach((item) => fTitle.push(this.fb.control(item)));
console.log(this.myForm.value);
}
ngOnInit(){
this.callApi();
}
In the child component, I am trying to filter the memberList
with an memberid that is passed in the form group.
export class HelloComponent {
public memberScheduleNotifications = [];
public memberList = [
{ id: 2, name: 'a' },
{ id: 1, name: 'b' },
{ id: 3, name: 'c' },
{ id: 4, name: 'd' },
];
@Input() myForm: FormGroup;
ngOnInit() {
this.memberFilter();
}
memberFilter() {
const member = this.myForm.controls.memberid as FormArray;
this.memberScheduleNotifications = member.value || [];
this.memberList = this.memberList.map((x) =>
this.memberScheduleNotifications.find((y) => y == x.id)
? { ...x, selected: true }
: { ...x }
);
}
}
Component
@Component({
selector: 'hello',
template: `
<div >
<p>child component</p>
<pre> {{memberList | json}}</pre>
</div>
`,
styles: [`h1 { font-family: Lato; }`],
})
Here the member list is not filtered with the member id passed from the parent component. The view is displayed without the filter being applied.
The child component not listening to the changes in the parent form array, which is updated through the API call.
What I am doing wrong here?