在Angular中从父级更新子级组件

时间:2020-10-27 18:07:25

标签: javascript angular

我一直在努力使其在Angular中工作。我有一个主机组件(父组件),该组件使用子组件来呈现下拉列表。列表的来源是从父级传递过来的。因此,例如,如果父级在source属性上传递了5个项目,则子级组件将为下拉列表呈现5个选项。

这是我称之为子组件的代码的一部分:

parent.component.html

<ng-container>
   <th mat-header-cell *matHeaderCellDef>
         <app-column-header
            [id]="column.id"
            [name]="column.name"
            [source]="myObject.options"
          ></app-column-header>
   </th>
</ng-container>

parent.component.ts

export class ParentComponent  {  

@ViewChild(ChildComponent) ChildComponent;  

 // more code

  private updateChildSource() {
    this.child.updateDataSource(myObject.options);
  }
}

到目前为止,这个方法还可以。

现在,我面临的挑战是要传递的项目列表必须是动态的(myObject.options)。因此,例如,第一次让我说我通过了5个项目。 Angular接受这5个项目并正确渲染子组件。但是,一旦子组件已经被渲染,并且如果我将源更改为父项的2项而不是5项并传递新的源,则子组件将不会渲染新项(2)。

child.component.ts

export class ColumnHeaderComponent implements OnInit, OnChanges {
  @Input() id: string;
  @Input() name: string;
  @Input() source: any[];

 childField: any;

  ngOnInit(): void {
    const options = this.doStuffHere(this.source);
    this.childField= {
      id: this.id,
      options,
    };
  }

  updateDataSource(newSource: Option[]): void {
     console.log(`print call from parent. old options: 
     ${JSON.stringify(this.childField.options)} - new options: ${JSON.stringify(newSource)}`);
     this.source= newSource;
     const options = this.doStuffHere(this.source);
     this.childField= {
       id: id,
       options,
     };
  }

  ngOnChanges(changes: SimpleChanges) {
    console.log('changed');     
    for (const propName in changes) {
      const chng = changes[propName];
      const cur  = JSON.stringify(chng.currentValue);
      const prev = JSON.stringify(chng.previousValue);
      console.log(`${propName}: currentValue = ${cur}, previousValue = ${prev}`);
    }
  }
}

如前所述,子组件正在接收原始项目和新项目,即使ngOnChanges方法也正在捕获它并正确打印值。但是由于某种原因,我还不知道子组件仍在渲染旧项目(5个)而不是新项目(2个)。

不确定,如果我在这里缺少什么?还是这个问题很清楚,足以说明我面临的问题。

您能指出正确的方向如何解决这个问题吗?预先感谢。

1 个答案:

答案 0 :(得分:1)

正如Marek所说,您可以直接从父组件传递列表作为子组件的输入。 [list] =“ list”表示法已经是反应性的。 然后,您只需要使用子组件中下拉列表中的列表即可。

注意:这里没有用,但是作为@Input,您可以设置函数而不是变量。每次输入值更改时都会触发。