我试图创建可以使用指令传递参数的子组件,但我仍然找不到任何创建itu的教程。
我从中尝试了一些方法:获取对组件中使用的指令的引用
这是我的代码
这是父组件的模板
<child-component>
<grand-child-directive [name]='Ghandy'></grand-child-directive >
<grand-child-directive [name]='Ani'></grand-child-directive >
<grand-child-directive [name]='Budi'></grand-child-directive >
</child-component>
这个孙子指令
@Directive({
selector: 'grand-child-directive ',
})
export class gc{
@Input() name:string;
}
这是我的孩子
@Component({
selector: 'child-component',
templateUrl: './child-component.component.html',
styleUrls: ['./child-component.component.scss'],
})
export class childComponent implements OnInit
@ViewChildren(gc) gc: gc;
constructor(
) {
}
ngOnInit() {
console.log(gc.name)
}
}
当我console.log gc.name时,我不确定,而不是数组[Ghandy,Ani,Budi]
我很乐意提供任何帮助。
您应该使用ContentChildren而不是ViewChildren。然后,您应该实现AfterContentInit生命周期挂钩以访问该值。
@Component({
selector: 'child-component',
templateUrl: './child-component.component.html',
styleUrls: ['./child-component.component.scss'],
})
export class childComponent implements OnInit,AfterContentInit
@ContentChildren(GrandChildDirective) gc:QueryList<GrandChildDirective> ;
constructor(
) {
}
ngAfterContentInit() {
console.log(this.gc.toArray().map(item=>item.name));
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句