I'm creating components in an ngFor and wondering why they don't update properly. Here is a stackblitz: https://stackblitz.com/edit/angular-ivy-naoejz?file=src%2Findex.html
Basically, when I update and tab out of the child components I add then submit the form the values are blank and I'd like to know why?
I know I could use FormBuilder, FormGroup and FormArray like this post: angular material stepper add new step items dynamically on every click , but I'm curious why what I'm doing doesn't work.
app.component.html
....
<app-child *ngFor="let child of childArray;let i = index;" [index]=i [childArray]=childArray>
</app-child>
<button type="button" (click)="addChildComponent()" > Add</button>
app.component.ts
....
export class AppComponent {
title = 'ng-example';
childArray: Array<ChildComponent>;
fields = {
myName : {
value:'testName'
},
myDesc: {
value:'testDesc'
}
};
addChildComponent(){
this.childArray.push(new ChildComponent());
}
onSubmit() {
const formData: any = new Object();
const childData = [];
console.log(this.childArray.length);
this.childArray.forEach((child) => {
const { myValue } = child.fields;
childData.push({
'childVal': myValue.value
});
});
formData.childData = childData;
//childData array has objects with childVal = '', why??
}
ngOnInit() {
this.childArray = new Array<ChildComponent>()
}
child.component.ts
....
export class ChildComponent {
@Input() index : number;
fields = {
myValue : {
value:''
}
};
inputBlur(event, fieldName) {
this.fields[`${fieldName}`].value = event.target.value;
}
}
child.component.html ....
<div>
<input name="myInfo{{index}}" (focusout)="inputBlur($event, 'myValue')" />
</div>