ContentChild由扩展的抽象类 [英] ContentChild by extended abstract class

查看:81
本文介绍了ContentChild由扩展的抽象类的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有两个不同的组件扩展了一个公共组件。

I have two different components that extend a common one.

AComponent extends BaseComponent {}
BComponent extends BaseComponent {}

第三个成分具有ng含量。

There is a third component that has ng-content.

<wrapper>
  <a-component></a-component>
  <b-component></b-component>
</wrapper>

不幸的是,在以下情况下这些组件不可见。

Unfortunately those component aren't visible in below scenario.

WrapperComponent {
  @ContentChildren(BaseComponent) components;
}

我不想创建具有特定类型的ContentChild(Acomponent,BComponnet) 。

I don't want to create ContentChild with specific types (Acomponent, BComponnet).

推荐答案

您可以使用别名的类提供程序作为解决方法。

you can use Aliased class providers as a workaround.

按如下所示定义组件;

Define your components as follows;

@Component({
  selector: 'a-component',
  templateUrl: './a.component.html',
  styleUrls: ['./a.component.css'],
  providers: [{ provide: BaseComponent, useExisting: AComponent }]
})
export class AComponent extends BaseComponent implements OnInit {
  constructor() {
    super();
    console.log("a created.");
  }

  ngOnInit() {}
}

and

@Component({
  selector: 'b-component',
  templateUrl: './b.component.html',
  styleUrls: ['./b.component.css'],
  providers: [{ provide: BaseComponent, useExisting: BComponent }]
})
export class BComponent extends BaseComponent implements OnInit {
  constructor() {
    super();
    console.log("b created.");
  }

  ngOnInit() {}
}

其中 BaseComponent

export abstract class BaseComponent {}

按如下所示在 WrapperComponent 中使用它

@Component({
  selector: 'wrapper',
  templateUrl: './wrapper.component.html',
  styleUrls: ['./wrapper.component.css']
})
export class WrapperComponent implements OnInit, AfterContentInit {
  @ContentChildren(BaseComponent) components;

  constructor() { }

  ngOnInit() { }

  ngAfterContentInit() {
    console.log("components: ", this.components.length);
  }
}

这是一个有效的演示 https://stackblitz.com/edit/angular-ynqhwj

这篇关于ContentChild由扩展的抽象类的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆