英文:
Get the component (of which I don't know the instance class) from the one passed to <ng-content>
问题
以下是翻译好的部分:
我有这个组件:
@Component({
selector: 'my-container',
template: `
<div class="my-container">
<div #wrapper class="my-container-body">
<ng-content></ng-content>
</div>
<div class="my-container-footer"></div>
</div>
`
})
export class MyContainer implements AfterViewInit {
@ViewChild('wrapped') item: ElementRef;
ngAfterViewInit() {
console.log('wrapped item is: ' + this.item.nativeElement);
}
}
例如,他们可以这样使用我的包装:
<my-container>
<some-component></some-component>
<my-container>
正如你所看到的,我可以使用@ViewChild
来访问包装的组件。但是,我想访问传递给<ng-content></ng-content>
的组件实例,但也许这不起作用,因为我不知道要使用的正确类型,因为我不知道传递给我的包装的组件是什么类型。对于@ContentChild
也是一样的情况。
我做错了什么吗?如何访问传递的任何组件的属性和方法?
英文:
I have this component:
@Component({
selector: 'my-container',
template: `
<div class="my-container">
<div #wrapper class="my-container-body">
<ng-content></ng-content>
</div>
<div class="my-container-footer"></div>
</div>
`
})
export class MyContainer implements AfterViewInit {
@ViewChild('wrapped') item: ElementRef;
ngAfterViewInit() {
console.log('wrapped item is: ' + this.item.nativeElement);
}
}
For example they can use my wrapped in the following way:
<my-container>
<some-component></some-component>
<my-container>
As you can see I can access to wrapped component, using @ViewChild
.
Instead I would like to access to the component instance that is passed to <ng-content></ng-content>
, but maybe it couldn't work because I don't know what is the right type to use since I don't know what kind of component is passed to my wrapper.
The same occurs with @ContentChild
.
Am I doing something wrong? How to access to properties and methods of the passed component that could be any component?
答案1
得分: 1
@ContentChild(NgControl) wrappedControl: NgControl;
英文:
As you need something exact from the content component (in your case it is a NgControl) it would be more logical to query for control, not the whole component.
@ContentChild(NgControl) wrappedControl: NgControl;
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论