내 질문은 그래서 여기에 또 다른 질문에 대한 확장입니다 : Angular2 and class inheritance support각 2
을 그리고 여기 내 plunckr입니다 :
필자는 모든 구성 요소를 사용해야하는 공통된 기능을 가지고 있습니다. 앞서 언급 한 질문에서 이미 답을 얻었으므로이 작업을 수행 할 수 있습니다.
내 질문은 : 기본 구성 요소에 종속성을 주입 할 수 있습니까? 내 plunkr에서 선언 된 종속성 (FormBuilder
)은 콘솔에 기록 될 때 정의되지 않았습니다.
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 {
// Interesting stuff 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 {
}
아니요, 기본 클래스에서 특수 효과를 상속 할 수 없기 때문에 가능하지 않습니다. 하지만 Thierry Templier의 대답이이 문제를 해결하는 데 도움이 될 수 있습니다. http://stackoverflow.com/a/36837482/1961059 – rinukkusu