I have 3 components. 1 parent component that can wrap one of any 2 child components inside an ng-content. My child components have shared functionality so they are extending an abstract class that have the shared functionality.
When I try to use ContentChildren to get the ng-content reference, it works fine if I am using one of the child classes. When I reference the abstract class, it does not work. Is there a way to make this work? plkr is: http://plnkr.co/edit/f3vc2t2gjtOrusfeesHa?p=preview
Here is my code:
Child abstract class:
abstract export class Child{
value: any;
abstract setValue();
}
My parent code:
@Component({
selector: 'parent',
template: `
<div>
parent
<ng-content></ng-content>
</div>
`,
})
export class Parent {
@ContentChild(Child)
child: Child;
name:string;
constructor() {
}
ngAfterViewInit() {
this.child.setValue();
}
}
First child:
@Component({
selector: 'child1',
template: `
<div>
value is: {{value}}
</div>
`,
})
export class Child1 extends Child {
name:string;
constructor() {
}
setValue() {this.value = 'Value from child 1'}
}
Second child:
@Component({
selector: 'child2',
template: `
<div>
value is: {{value}}
</div>
`,
})
export class Child2 extends Child {
name:string;
constructor() {
}
setValue() {this.value = 'Value from child 2'}
}
I solved this by using:
into my Component decorator for Child1
providers: [{provide: Child, useExisting: forwardRef(() => Child1)}],
into my Component decorator for Child2
providers: [{provide: Child, useExisting: forwardRef(() => Child2)}],
You can now look at the new io example from angular:
https://angular.io/guide/dynamic-component-loader
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With