As a continuation of the discussion on Angular2 and class inheritance support here on SO, I have a question:
Check out my plunckr example: http://plnkr.co/edit/ihdAJuUcyOj5Ze93BwIQ?p=preview
Here is what I am attempting to achieve:
I want to implement some shared functionality that all my components will need to utilize. According to the answers in the aforementioned thread, this can be done.
My specific query is: Is it possible to inject dependencies into the base-component? In my plunker demo, the declared dependency (FormBuilder
) appears undefined when logged to the console.
import {AfterContentChecked, Component, ContentChildren, Input, QueryList, forwardRef, provide, Inject} from '@angular/core';
import { FormGroup, FormControl, Validators, FormBuilder, REACTIVE_FORM_DIRECTIVES } from '@angular/forms';
@Component({
providers: [FormBuilder]
})
export class BaseComponent {
// Relevant code here
@Input() id: string;
constructor(formBuilder: FormBuilder){
console.log(formBuilder);
console.log('inside the constructor');
}
}
@Component({
selector: 'child-comp2',
template: '<div>child component #2 ({{id}})</div>',
providers: [provide(BaseComponent, { useExisting: forwardRef(() => ChildComponent2) })]
})
export class ChildComponent2 extends BaseComponent {
}
@Component({
selector: 'child-comp1',
template: '<div>child component #1 ({{id}})</div>',
providers: [provide(BaseComponent, { useExisting: forwardRef(() => ChildComponent1) })]
})
export class ChildComponent1 extends BaseComponent {
}
@Component({
selector: 'parent-comp',
template: `<div>Hello World</div>
<p>Number of Child Component 1 items: {{numComp1}}
<p>Number of Child Component 2 items: {{numComp2}}
<p>Number of Base Component items: {{numBase}}
<p><ng-content></ng-content>
<p>Base Components:</p>
<ul>
<li *ngFor="let c of contentBase">{{c.id}}</li>
</ul>
`
})
export class ParentComponent implements AfterContentChecked {
@ContentChildren(ChildComponent1) contentChild1: QueryList<ChildComponent1>
@ContentChildren(ChildComponent2) contentChild2: QueryList<ChildComponent2>
@ContentChildren(BaseComponent) contentBase: QueryList<BaseComponent>
public numComp1:number
public numComp2:number
public numBase:number
ngAfterContentChecked() {
this.numComp1 = this.contentChild1.length
this.numComp2 = this.contentChild2.length
this.numBase = this.contentBase.length
}
}
@Component({
selector: 'my-app',
template: `<parent-comp>
<child-comp1 id="A"></child-comp1>
<child-comp1 id="B"></child-comp1>
<child-comp2 id="C"></child-comp2>
</parent-comp>
`,
directives: [ParentComponent, ChildComponent1, ChildComponent2]
})
export class MyApplication {
}