【问题标题】:Child component data not getting updated from parent component子组件数据未从父组件更新
【发布时间】:2019-02-17 09:18:47
【问题描述】:

我正在尝试将列表从父组件发送到子组件,以将其绑定到垫子自动完成功能。

下面是我的父组件 //父组件.html

<mat-card style="margin: 1px;">
  <search-form [(messageTypeList)]="messageTypeList" [rowData]="rowData | async">
  </search-form>
</mat-card>

在我的父组件 ts 文件中

//parentcomponent.ts

messageTypeList: Messagetype[] = [];

ngOnInit() {
const messageTypeList = this.store.select(fromStore.getMessageTypeListData);
messageTypeList.pipe(takeUntil(this.unsubscribe$)).subscribe(msgTypeList => {
  if (msgTypeList.length > 0) {
    for (var i = 0; i < msgTypeList.length; i++) {
      this.messageTypeList.push(msgTypeList[i]); // this messageTypeList is send to child component
    }
  }
  else {
    this.store.dispatch(new fromStore.GetMessageTypeList({}));
  }
})

下面是我的子组件

 //childcomponent.ts
 @Input() messageTypeList: Messagetype[];

ngOnInit() {
 console.log('messagetypelist='+this.messageTypeList); // getting data as []
}

parent 初始化后,child 初始化,但异步 ngrx 调用仍未完成,因此 child 中还没有数据(在 ngOnInit 中)

点击ngOnInitin 子项后,然后在父项中,msgTypeList 被填充(异步调用已完成),但现在没有将可用数据发送给子项

我是否必须转换为 observable 才能获取更新的数据,还是有其他方法。

【问题讨论】:

    标签: angular typescript observable parent-child angular6


    【解决方案1】:

    抱歉,我不太了解 ngOnInit 内部代码的目标。

    调用选择器应该返回 Observable。 然后你只需要通过管道将 observable 传递给你的组件。

    所以请你试试这个,如果它可以帮助你。这是它可以是什么(按照你的代码):

    //parentcomponent.html
    
    <mat-card style="margin: 1px;">
      <search-form [messageTypeList]="messageTypeList$ | async" [rowData]="rowData | async">
      </search-form>
    </mat-card>
    

    父组件TS文件

    //parentcomponent.ts
    
    messageTypeList$: Observable<Messagetype[]>;
    
    ngOnInit() {
      this.messageTypeList$ = this.store.select(fromStore.getMessageTypeListData);
    
      // only if you need to load data into store before...
      this.store.dispatch(new fromStore.LoadMessageType({}));
    })
    

    子组件

    //childcomponent.ts
    @Input() messageTypeList: Messagetype[];
    
    ngOnInit() {
     console.log('messagetypelist=', this.messageTypeList);
    }
    

    【讨论】:

      猜你喜欢
      • 2023-03-11
      • 2019-12-09
      • 2017-04-16
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-02-20
      相关资源
      最近更新 更多