javascript - 在 ngFor 中创建的组件没有正确更新
问题描述
我在 ngFor 中创建组件,想知道为什么它们不能正确更新。这是一个堆栈闪电战:https ://stackblitz.com/edit/angular-ivy-naoejz?file=src%2Findex.html
基本上,当我更新并从我添加的子组件中取出然后提交表单时,值是空白的,我想知道为什么?
我知道我可以像这篇文章一样使用 FormBuilder、FormGroup 和 FormArray:angular material stepper add new step items dynamic on each click,但我很好奇为什么我正在做的事情不起作用。
应用程序.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>
应用程序.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>
解决方案
我正在编写一些伪代码只是为了让您易于理解
app.component.ts
// the custom field object
class Field {
id?: string;
value?: string;
}
class AppComponent {
// this is the fields array
fields: Field[] = [
{
id: "myName",
value: "Test Name"
},
{
id: "myDesc",
value: "Test Desc"
}
];
onSubmitClick() {
console.log(this.fields); // here you ll get what you want
}
}
app.component.html
<app-child ngFor="let field of fields" [field]="field"></app-child>
<button (click)="fields.push({})">add</button>
<button (click)="onSubmitClick()">submit</button>
child.component.ts
class ChildComponent {
@Input('field') field: Field;
}
child.component.html
<input #input type="text" (input)="field.value = input.value" />
我还没有测试过代码,但它可以满足你的需求。
推荐阅读
- git - 连接到 gitlab 时使用 ssh 面临身份验证失败
- vba - VBA Pivot取消选择值以选择单个值
- ms-access - 使用注册表检测 office 365(访问)和 Visual C 64x
- python - While循环并在python中调用函数
- initialization - Pytorch:1.2.0 - AttributeError:“Conv2d”对象没有属性“权重”
- javascript - 为某些移动设备/浏览器提交表单后 Gif 未加载
- node.js - 轨迹第一次运行以进行后续运行我得到“开始”的值超出范围。它必须 >= 0 并且 <= 2 ** 53 - 1。收到 -25586
- javascript - 将文本动态添加到 jQuery 选取框
- python - 如何在 Python 中使用 httpx(相对于 aiohttp)发出并行异步 HTTP 请求?
- python - 如何使用 Selenium Python 只点击一定数量的 URL 链接?