基本上不是这样做:
class Controller implements AfterViewInit{
@ViewChild(IconComponent)
iconComponent: IconComponent;
ngAfterViewInit() {
iconComponent.save();
}
}
我想要一个这样的组件:
class Controller implements AfterViewInit{
ngAfterViewInit() {
const iconComponent = someRef.get(IconComponent); // where to get this component from
iconComponent.save()
}
}
我该如何实现这一点?
我之所以问这个问题,是因为我在运行时获得组件类型,而不是在编译时。
发布于 2019-04-10 15:23:27
为什么不使用提供的ComponentFactoryResolver
创建组件
通过这种方式,您可以获取其componentRef并管理其实例。
下面是ComponentFactoryResolver的文档,您可以在其中找到一个很好的实现example。
发布于 2019-04-19 19:12:22
您可以拥有一个注入令牌。即使类型会导致错误(因此类型转换为any),这也是可行的:
@ViewChild(YOUR_TOKEN as any)
component: YourAbstractClass;
或者,如果您通过某个模板引用变量将它们全部标记:
@ViewChild('some', {read: YOUR_TOKEN})
component: YourAbstractClass;
从抽象类派生的所有组件都应提供此令牌:
@Component({
selector: 'your-component',
templateUrl: './yourComponent.template.html',
styleUrls: ['./yourComponent.style.less'],
providers: [
{
provide: YOUR_TOKEN,
useExisting: forwardRef(() => YourComponent ),
},
],
})
export class YourComponent extends YourAbstractClass {
这样,您还可以将它们全部注入到指令中。
https://stackoverflow.com/questions/55606777
复制相似问题