如何不通过 HTML 将数据传递给组件

问题描述 投票:0回答:1

我有一个组件,我引用了另一个组件。

readonly componentA: typeof ComponentA = ComponentA;

我想从我在

ngOnInit
方法中有这个引用的组件传递一个值。实现这一目标的最佳方法是什么?现在我用

this.componentA.prototype.myVariable = value;

是否可以一直这样,还是换一种方式更好?

angular
1个回答
0
投票

您可以使用 @ViewChild() 装饰器并在 ngAfterViewInit 生命周期钩子中设置值。

export class ParentComponent implements AfterViewInit {
 @ViewChild(ComponentA) component;

 ngAfterViewInit() {
  this.component.inputName = 'my value';
 }
}

这里是 stackblitz 示例的链接https://stackblitz.com/edit/angular-playground-ovfzqg?file=app/app.component.ts

© www.soinside.com 2019 - 2024. All rights reserved.