我正在使用Angular 2.0.1.
我有一个组件可以通过< ng-content>接收任何其他组件. – 这很棒.
我遇到的问题是当我想引用注入的组件时.
如果我知道< ng-content>只会是我能说的一个组成部分:
@ContentChild(MyComponent)dynamicTarget:IMyComponent;但是因为它可能是任何组件(我将做的唯一假设是任何注入的组件实现特定的接口)它变得更加棘手.
我也试过< ng-content#dynamicTarget'>然后通过说@ContentChild(‘dynamicTarget’)dynamicTarget:IMyComponent来引用它;但这会返回undefined.
有谁知道我怎么能告诉Angular 2这个东西是一个组件的实例,以便我可以尝试调用它上面的函数?
为了进一步说明用例 – 我有一个多步骤向导,可以将任何组件作为内容,我想在内容上调用validate函数(我将假设存在于所述实例上)
解决方法
一种方法可以是为任何动态组件提供相同的#id.
我给了#thoseThings. (我认为它与@Missingmanual几乎相同)
我给了#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 { }