【发布时间】:2020-11-11 07:55:56
【问题描述】:
我有一个父组件,里面有子指令。需要从指令中的组件获取输入数据。
<my-parent [data]="'Hello from parent'">
<input myChild>
</my-parent>
父组件
@Component({
selector: 'my-parent',
template: `
<ng-content select="[myChild]"></ng-content>
`
})
export class ParentComponent {
@Input() data: string;
}
儿童指令
@Directive({
selector: '[myChild]'
})
export class ChildDirective implements OnInit {
value: string;
ngOnInit() {
// needs to get data from parent component here
}
}
我可以将父组件注入指令,但我不想这样做,因为它增加了循环依赖的风险。
我可以在 ParentComponent 中使用 @ContentChild 并通过公共属性在 AfterContentInit 中传递数据,但我不确定此属性何时可以在 ChildDirective 中使用,我应该在这种情况下使用 AfterContentChecked 吗?
父组件
@ContentChild(ChildDirective, {static: true}) child: ChildDirective;
ngAfterContentInit() {
this.child.value = this.data;
}
儿童指令
value: string;
ngAfterContentChecked() {
// will be available data from parent here?
}
也许我应该使用服务在组件和指令之间共享数据?
https://stackblitz.com/edit/angular-pass-data-to-child-directive
【问题讨论】:
标签: angular angular-directive angular-components angular9