Angular 使用指令将参数传递给子组件
我试图创建可以使用指令传递param的子组件,但仍然没有找到任何创建itu的教程 我试过一些: 这是我的密码 这是来自父组件的模板Angular 使用指令将参数传递给子组件,angular,typescript,Angular,Typescript,我试图创建可以使用指令传递param的子组件,但仍然没有找到任何创建itu的教程 我试过一些: 这是我的密码 这是来自父组件的模板 <child-component> <grand-child-directive [name]='Ghandy'></grand-child-directive > <grand-child-directive [name]='Ani'></grand-child-directive >
<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>
这是我的子组件
<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>
@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));
}
}
@组件({
选择器:'子组件',
templateUrl:“./child component.component.html”,
样式URL:['./子组件.component.scss'],
})
导出类childComponent实现OnInit,AfterContentInit
@ContentChildren(指令)gc:QueryList;
建造师(
) {
}
ngAfterContentInit(){
log(this.gc.toArray().map(item=>item.name));
}
}
为什么要将指令投射到组件中?@Chellappan,我需要处理子组件中的名称([Ghandy,Ani,Budi]),除了名称之外,我还需要其他类似Address的内容为什么不在子组件中使用
@Input()
。