【问题标题】:Component created in ngFor is not updating properly在 ngFor 中创建的组件没有正确更新
【发布时间】: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


【解决方案1】:

我写一些伪代码只是为了方便你理解

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

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

【讨论】:

  • 这正是我要找的。也感谢您的解释。
【解决方案2】:

您无权访问子组件的字段更改。为此,您需要使用 @ViewChildren 和 QueryList。

import { Component, QueryList,  ViewChild, ViewChildren } from '@angular/core';
import { ChildComponent } from './child/child.component';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'ng-example';
  childArray: Array<ChildComponent>;
  @ViewChildren(ChildComponent) children1: QueryList<ChildComponent>;

  fields = {
    myName : {
      value:'testName'
    },
    myDesc: {
      value:'testDesc'
    }
  };

  inputBlur(event, fieldName) {
    this.fields[`${fieldName}`].value = event.target.value;
  }

  addChildComponent(){
    this.childArray.push(new ChildComponent());
  }

  onSubmit() {
    const formData: any = new Object();

    const childData = [];
    this.children1.toArray().forEach((child) => {
      const { myValue } = child.fields;
      childData.push({
        'childVal': myValue.value
      });
    });
    formData.childData = childData;

    console.log(formData);
  }

  ngOnInit() {
    this.childArray = new Array<ChildComponent>()
  }
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2020-12-11
    • 2020-01-07
    • 2023-03-11
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-03-16
    相关资源
    最近更新 更多