我创建一个包含组件的指令:HomechildrenComponent
<p>{{name}}</p>
<address>
<strong>Twitter, Inc.</strong><br>
1355 Market St, Suite 900<br>
San Francisco, CA 94103<br>
<abbr title="Phone">P:</abbr> (123) 456-7890
</address>
和指令
@Directive({
selector: '[appRenderhomechildcp]'
})
export class RenderhomechildcpDirective {
private name : string;
@Input('appRenderhomechildcp') set appRenderhomechildcp(name : string){
this.name = name;
};
childComponent : ComponentRef<HomechildrenComponent>;
constructor(private container : ViewContainerRef, private cpFactoryResolve : ComponentFactoryResolver)
{
const componentFactory = this.cpFactoryResolve.resolveComponentFactory(HomechildrenComponent);
this.childComponent = this.container.createComponent(componentFactory);
this.childComponent.instance.name = this.name;
}
在我将指令调用到 Home.Component.ts 后
lsFood = ['Candy', 'Milk', 'Juice fruite', 'Cream']
<div *ngFor="let item of lsFood">
<div [appRenderhomechildcp]="item"></div>
</div>
但它无法将 HomeComponent 中的数据绑定(bind)到指令。我该如何处理? 谢谢
最佳答案
您的 @Input
属性尚未在构造函数中初始化。将 name
初始化移动到 ngOnInit钩子(Hook)并且它应该可以工作:
export class RenderhomechildcpDirective implement OnInit {
...
ngOnInit() {
this.childComponent.instance.name = this.name;
}
<强> Ng-run Example
关于angular - 在 Angular 9 中将数据传递给指令,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62496875/