【发布时间】:2020-09-27 15:15:22
【问题描述】:
我正在 ngFor 中创建组件,想知道为什么它们不能正确更新。这是一个堆栈闪电战:https://stackblitz.com/edit/angular-ivy-naoejz?file=src%2Findex.html
基本上,当我更新并从我添加的子组件中跳出标签然后提交表单时,值是空白的,我想知道为什么?
我知道我可以像这篇文章一样使用 FormBuilder、FormGroup 和 FormArray:angular material stepper add new step items dynamically on every click,但我很好奇为什么我正在做的事情不起作用。
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>
【问题讨论】:
-
我不会让你失去动力,但你把这件事复杂化了
-
这可以通过一种简单的方法来完成
-
我尝试改进你的代码,但并不容易让我给你简单的方法
-
在您的子组件中直接通过 @Input 接收一个对象并将值放入其中,该值应在 (input) 回调而不是 (inputBlur) 中更改,并循环遍历具有对象的数组您希望数据的类型和添加按钮单击只需将一个空对象推送到数组。如果你愿意,我可以为你写一些伪代码
-
我明白你在说什么,只是好奇为什么这不起作用。
标签: javascript angular