【问题标题】:Pass data to child component that can be called multiple times将数据传递给可以多次调用的子组件
【发布时间】:2020-04-03 08:52:28
【问题描述】:

我有一个父组件并使用 ViewChild 调用子组件中的方法。但是,当我加载数据并使用该方法传递数据时,它显示错误我的方法未定义。我哪里弄错了?

流程: 首先:在 NgOnInit() 方法之后,我加载数据并将其传递给子组件 第二次尝试:我使用 NgAfterViewInit() 加载数据端然后将其传递给子组件但它有相同的错误

注意:父组件有一个变量可以多次创建子组件

带有更多description的示例代码:

【问题讨论】:

  • Hi NguYen 欢迎来到 SO。能否请您也包含代码
  • 请使用 stackblitz 复制您的示例并发布链接或添加您的父/子 ts 文件的内容。
  • 这里是:stackblitz.com/edit/angular-t917aq。示例代码与我的有关。我有一些描述让它更清楚
  • 请将此代码示例发布到您的问题中以供将来参考。寻找相同问题的其他用户以后可能不会再找到您的链接。 stackoverflow.com/help/minimal-reproducible-example

标签: angular angular-material


【解决方案1】:

您可以使用 @Input 装饰器将数据传递给孩子。理论:

  1. 通过这个input传递数据
  2. 火灾变化检测来处理这些变化 家长 TS:
@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';
}

父 HTML:

<app-child [name]="name"></app-child>

儿童 TS:

import { Component } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './app-child.component.html',
  styleUrls: [ './app-child.component.css' ]
})
export class AppChildComponent  {
  @Input() name = '';

  ngOnChanges(changes: SimpleChanges): void {
    if (changes.name) {
      this.setup();
    }
  }

  setup() {
     ...
  }
}

在孩子的内部设置中,您可以按预期处理数据。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2021-01-28
    • 1970-01-01
    • 2017-12-29
    • 2021-12-27
    • 2023-01-25
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多