【问题标题】:How to pass dynamic data to child component in angular 4?如何将动态数据传递给角度 4 中的子组件?
【发布时间】:2020-03-16 18:28:35
【问题描述】:

我有一个父组件,一旦我将在父组件中收到响应,我必须将数据传递给子组件。

挑战

1) 我必须等待传递数据,直到我在父组件中收到响应。

2) 一旦收到子组件的数据,我想在子组件中执行特定功能。

Parent.component.ts

JSON.parse(this.responseData, (key, value) => {
 if (key === 'patient-list') {
      this.mrn = this.totalPatientList[0]['value']['patientmrn'];
}
});

Parent.component.html

<router-outlet></router-outlet>

Child.component.html

@Input() patientdata:any;


ngAfterViewChecked(){
console.log('Data Received -----', this.patientdata);    
}

我希望我能够向大家解释我的问题。

【问题讨论】:

  • 而不是 我可以调用父组件中的子组件

标签: angular typescript


【解决方案1】:

您的示例中没有子/父通信,因为它要求组件直接位于父 component.html 中。

您需要依靠警卫解析器才能在数据接收时加载“孩子”。

【讨论】:

    【解决方案2】:

    您正在使用路由,也许最好的方法是使用单例服务来进行两个组件的通信。

    【讨论】:

      【解决方案3】:
      1. 使用Services 在多个组件之间传递数据。
      2. 处理后传递数据返回Observer而不是数据,一旦数据返回正确,将通知其他组件。

      【讨论】:

        【解决方案4】:

        所有其他答案都是明智的,并且可以正常工作。

        另一种方法是使用@ngrx 来管理状态并启用到组件的单向数据流。

        【讨论】:

          【解决方案5】:

          我在将动态数据从父级传递给子级时遇到问题,进行了全面搜索,但没有得到任何帮助。最后我尝试了这个,它对我非常有用。试试这个,它可能对你有帮助。

          子组件:

          export class ChildComponent {
            @Input() title: string;
          
            //rest code goes here...
          }
          

          父组件:

          export class ParentComponent {
                  headerTitle: string = '';
          
                  //rest code ...
          //on click changing the value
                  onHeaderChange() {
                      this.headerTitle = "MyHeader";
                  }
              }
          

          在父组件 html 文件中放置代码,如下所示,带单引号

          <child-component [title]='headerTitle'></child-component>
          

          【讨论】:

            猜你喜欢
            • 2017-11-20
            • 2018-02-14
            • 2018-05-08
            • 2018-06-05
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 1970-01-01
            • 2021-12-22
            相关资源
            最近更新 更多