Han*_*nna 6 typescript angular2-ngcontent angular
我正在使用Angular 2.0.1。
我有一个可以通过其他任何组件使用的组件<ng-content>-效果很好。
我遇到的问题是当我想引用注入的组件时。
如果我知道那<ng-content>将永远只是一个组件,我可以说:
@ContentChild(MyComponent) dynamicTarget: IMyComponent;但是因为它可以是任何组件(我要做出的唯一假设是任何注入的组件都实现了特定的接口),所以变得棘手。
我也尝试过<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 {
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1817 次 |
| 最近记录: |