[英]ContentChild by extended abstract class
I have two different components that extend a common one. 我有两个不同的组件,它们扩展了一个共同的组件。
AComponent extends BaseComponent {}
BComponent extends BaseComponent {}
There is a third component that has ng-content. 第三个组件具有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;
}
I don't want to create ContentChild with specific types (Acomponent, BComponnet). 我不想使用特定类型(Acomponent,BComponnet)创建ContentChild。
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() {}
}
where BaseComponent
is BaseComponent
在哪里
export abstract class BaseComponent {}
use it in the WrapperComponent
as follows 在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);
}
}
here is a working demo https://stackblitz.com/edit/angular-ynqhwj 这是一个有效的演示https://stackblitz.com/edit/angular-ynqhwj
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.