一种方法是为#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 {
}