首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何动态获取子组件,而不是使用@ViewChild

如何动态获取子组件,而不是使用@ViewChild
EN

Stack Overflow用户
提问于 2019-04-10 15:15:27
回答 2查看 981关注 0票数 4

基本上不是这样做:

代码语言:javascript
复制
class Controller implements AfterViewInit{
  @ViewChild(IconComponent)
  iconComponent: IconComponent;

  ngAfterViewInit() {
    iconComponent.save();
  }

}

我想要一个这样的组件:

代码语言:javascript
复制
class Controller implements AfterViewInit{

  ngAfterViewInit() {
    const iconComponent = someRef.get(IconComponent); // where to get this component from
    iconComponent.save()
  }

}

我该如何实现这一点?

我之所以问这个问题,是因为我在运行时获得组件类型,而不是在编译时。

EN

回答 2

Stack Overflow用户

发布于 2019-04-10 15:23:27

为什么不使用提供的ComponentFactoryResolver创建组件

通过这种方式,您可以获取其componentRef并管理其实例。

下面是ComponentFactoryResolver的文档,您可以在其中找到一个很好的实现example

票数 0
EN

Stack Overflow用户

发布于 2019-04-19 19:12:22

您可以拥有一个注入令牌。即使类型会导致错误(因此类型转换为any),这也是可行的:

代码语言:javascript
复制
@ViewChild(YOUR_TOKEN as any)
component: YourAbstractClass;

或者,如果您通过某个模板引用变量将它们全部标记:

代码语言:javascript
复制
@ViewChild('some', {read: YOUR_TOKEN})
component: YourAbstractClass;

从抽象类派生的所有组件都应提供此令牌:

代码语言:javascript
复制
@Component({
    selector: 'your-component',
    templateUrl: './yourComponent.template.html',
    styleUrls: ['./yourComponent.style.less'],
    providers: [
        {
            provide: YOUR_TOKEN,
            useExisting: forwardRef(() => YourComponent ),
        },
    ],
})
export class YourComponent extends YourAbstractClass {

这样,您还可以将它们全部注入到指令中。

票数 -2
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/55606777

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档