【发布时间】:2019-06-30 15:51:21
【问题描述】:
我正在使用 Angular 7/8,我有一些代码添加了一个新组件,因此在父组件中我有:
父组件
在我的 .ts 文件中:
@ViewChild(InjectDirective) injectComp: InjectDirective;
constructor (private componentFactoryResolver: ComponentFactoryResolver) {}
addComponent() {
const componentFactory = this.componentFactoryResolver.resolveComponentFactory(ChildComponent);
const viewContainerRef = this.injectComp.viewContainerRef;
viewContainerRef.createComponent(componentFactory);
}
在 .html 中我有:
<button (click)="addComponent()">Add Component</button>
我还有一个指令:
import { Directive, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[appInject]'
})
export class InjectDirective {
constructor(public viewContainerRef: ViewContainerRef) {}
}
最后是子组件:
子组件:
然后在我的子组件中:
export class ChildComponent implements OnInit {
@ViewChild('viewer') private viewer: ElementRef;
}
在 html 中:
<div>I AM A COMPONENT</div>
我要做的是将数据传递给创建的子组件,以便每个子组件都可以拥有自己的数据。
我该怎么做:
【问题讨论】:
-
尝试创建一个
common service将数据从父级发送到子级或使用@Output装饰器和EventEmitter
标签: angular typescript angular7 angular8