首页 > 解决方案 > 在 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>

标签: javascriptangular

解决方案


我正在编写一些伪代码只是为了让您易于理解

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" />

我还没有测试过代码,但它可以满足你的需求。


推荐阅读