【问题标题】:Angular4 Passing data from parent to child, emit not workingAngular将数据从父母传递给孩子,发出不工作
【发布时间】:2018-05-03 13:44:41
【问题描述】:

我正在尝试将数据从父组件发送到子组件,但是我的 ng2-smart-table 存在发送方式的问题。在我的父组件中,我使用了使用 userRowSelect(标准函数)的 ng2-smart-table,当我在表中选择一行时,我会从该行获取所有数据。我想传递给我的子组件的那一行的数据。我尝试使用共享服务、输入和发射,到目前为止它们都没有工作。下面是这两个组件的代码 sn-ps。有什么建议吗?

父 html:

<ng2-smart-table [settings]="settings" [source]="data" (userRowSelect)="onRowSelect($event)"></ng2-smart-table>

父组件:

@Output() passDataToViewPdf: EventEmitter<any> = new EventEmitter();

  ngOnInit() {
      this.reportService.getReportsTemplates().subscribe(response => this.data = response);
  }

  onRowSelect(event): void {
      this.passDataToViewPdf.next(event);
      this.router.navigate(['/report-view-pdf', localStorage.getItem('siteId')]);
  }

子组件:

    @Input() template;

    public handleEvent(event) {
            // get data from passDataToViewPdf emitter
        }
    ngOnInit() { this.template = // get data from handleEvent}

【问题讨论】:

标签: angular input eventemitter emit ng2-smart-table


【解决方案1】:

那是因为 Angulars EventEmitteremit 方法来发出值。看docs

应该是

this.passDataToViewPdf.emit(event);

但是查看您的代码 EventEmitter 是在父组件中定义的,因此您的父组件正在向其父组件而不是子组件发送值。

它应该看起来像这样。

子组件

@Input() template;
@Input() set pdf(newPdf) {
   this._pdf = newPdf;
   this.handleEvent(newPdf);
};
private _pdf;



public handleEvent(event) {
    // process your data
}
ngOnInit() { this.template = // get data from handleEvent}

父 html 模板

<child-component [pdf]="pdfValueInParent"></child-component>

父组件ts

onRowSelect(event): void {
      this.pdfValueInParent = event;
      this.router.navigate(['/report-view-pdf', localStorage.getItem('siteId')]);
  }

【讨论】:

  • 我将我的子组件加载到不同的页面上,我通过父级 (/report-view-pdf) 中的 onRowSelect 函数路由到该页面。我没有在 parent-html 本身中包含子组件选择器。如果不将选择器包含在 parent-html 中,我如何仍将数据提供给我的孩子?
  • 好吧,那么你可以通过几种方式来做到这一点,首先是service,它存储数据并共享它。如果是小数据,可以使用localStorage,或者尝试通过router传递。最快和最安全的方法是将数据存储到service,然后从service 中的child-component 中获取数据。 (service 我的意思是小angular service 或者你可以制作singleton
  • 我已经有一个共享服务,路由或本地存储不是一个选项,因为我必须传递大量的 json 数据。我可以将共享服务用于大量数据,到目前为止我只在我的应用程序中使用它来将一个值从一个组件传递到另一个组件?
  • 然后使用您的shared service。这将是最好的选择。再存储一个变量应该不成问题:)
  • 下一个问题:我有我的共享服务,但是当订阅 observable 时,它​​总是在我的子组件中返回 null。路由是否会导致问题?
猜你喜欢
  • 2021-10-16
  • 1970-01-01
  • 2021-10-31
  • 1970-01-01
  • 2023-02-08
  • 2018-05-18
  • 2020-09-19
  • 2020-07-22
  • 2021-09-13
相关资源
最近更新 更多