[英]How to dynamically get child components instead of using @ViewChild
Basically instead of doing this:基本上不是这样做:
class Controller implements AfterViewInit{
@ViewChild(IconComponent)
iconComponent: IconComponent;
ngAfterViewInit() {
iconComponent.save();
}
}
I would like to get a component like this:我想得到一个这样的组件:
class Controller implements AfterViewInit{
ngAfterViewInit() {
const iconComponent = someRef.get(IconComponent); // where to get this component from
iconComponent.save()
}
}
How do I achieve this?我如何实现这一目标?
I am asking this question because I get the component type in the runtime, not compiletime.我问这个问题是因为我在运行时获得了组件类型,而不是编译时。
Why don't you create the component with the provided ComponentFactoryResolver
?为什么不使用提供的
ComponentFactoryResolver
创建ComponentFactoryResolver
?
By this way you can get its componentRef and manage its instance.通过这种方式,您可以获取其 componentRef 并管理其实例。
Here is the documentation of the ComponentFactoryResolver and you can find there a good implementation example .这是ComponentFactoryResolver的文档,您可以在那里找到一个很好的实现示例。
You can have an Injection Token.您可以拥有一个注入令牌。 Even though types would cause you errors (hence typecast to any), this would work:
即使类型会导致您出错(因此类型转换为 any),这也会起作用:
@ViewChild(YOUR_TOKEN as any)
component: YourAbstractClass;
Or, if you marked them all by some template reference variable:或者,如果你用某个模板引用变量标记了它们:
@ViewChild('some', {read: YOUR_TOKEN})
component: YourAbstractClass;
All components derived from your abstract class should provide this token:从抽象类派生的所有组件都应提供此标记:
@Component({
selector: 'your-component',
templateUrl: './yourComponent.template.html',
styleUrls: ['./yourComponent.style.less'],
providers: [
{
provide: YOUR_TOKEN,
useExisting: forwardRef(() => YourComponent ),
},
],
})
export class YourComponent extends YourAbstractClass {
This way you could also inject them all into directives.通过这种方式,您还可以将它们全部注入指令中。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.