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);
}
}