我正在使用 Angular 2.0.1。
我有一个组件可以通过 <ng-content>
接收任何其他组件-- 这很好用。
我遇到的问题是当我想引用注入(inject)的组件时。
如果我知道 <ng-content>
只会是我可以说的一个组成部分:
@ContentChild(MyComponent) dynamicTarget: IMyComponent;
但是因为它可能是任何组件(我唯一的假设是任何注入(inject)的组件都实现了一个特定的接口(interface))它变得更加棘手。
我也试过 <ng-content #dynamicTarget'>
然后通过说 @ContentChild('dynamicTarget') dynamicTarget: IMyComponent;
来引用它但这返回未定义。
有谁知道我如何告诉 Angular 2 这个东西是一个组件的实例,以便我可以尝试调用它的函数?
为了进一步阐明用例——我有一个多步骤向导,可以将任何组件作为内容,我想调用 validate
内容上的功能(同样,我假设存在于所述实例上)
最佳答案
一种方法是为任何动态组件提供相同的#id
。
我给了 #thoseThings
。 (我觉得和@Missingmanual差不多)
PLUNKER (有关比赛,请参阅控制台。)
@Component({
selector: 'my-app',
template: `
<div [style.border]="'4px solid red'">
I'm (g)Root.
<child-cmp>
<another-cmp #thoseThings></another-cmp>
</child-cmp>
</div>
`,
})
export class App {
}
@Component({
selector: 'child-cmp',
template: `
<div [style.border]="'4px solid black'">
I'm Child.
<ng-content></ng-content>
</div>
`,
})
export class ChildCmp {
@ContentChildren('thoseThings') thoseThings;
ngAfterContentInit() {
console.log(this.thoseThings);
this.validateAll();
if(this.thoseThings){
this.thoseThings.changes.subscribe(() => {
console.log('new', this.thoseThings);
})
}
}
validateAll() {
this.thoseThings.forEach((dynCmp: any) => {
if(dynCmp.validate)
dynCmp.validate(); // if your component has a validate function it will be called
});
}
}
@Component({
selector: 'another-cmp',
template: `
<div [style.border]="'4px solid green'">
I'm a Stranger, catch me if you can.
</div>
`,
})
export class AnOtherCmp {
}
关于Angular 2引用@ContentChild的动态实例,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40412289/