私はおそらくViewChildren
とContentChildren
とその実際的な使用法と混同しています。ViewChildernとContentChildernの違いと、両方を実質的に使用する方法は?
実際にどのように使用するか教えてください。彼らの目的は何ですか?
@Component({
selector: 'my-app',
template: `
<h4>ParentCmp</h4>
<button (click)="clicked()">show/hide</button>
<child> first child from childcmp </child>
<bR><bR>
<child *ngIf="show"> second child from childcmp </child>
<bR><bR>
<child1></child1>
`,
directives: [childcmp,child1cmp],
})
export class ParentCmp {
show:boolean=true;
@ViewChildren(childcmp) viewChildren: QueryList<childcmp>;
@ContentChildren(childcmp) contentChildren: QueryList<childcmp>;
ngAfterViewInit()
{
console.log('viewChildren-> ' + this.viewChildren.length);
console.log('contentChildren-> ' + this.contentChildren.length);
}
clicked()
{
this.show=!this.show;
this.viewChildren.changes.subscribe(() => console.log('viewChildren-> ' + this.viewChildren.length));
this.contentChildren.changes.subscribe(() => console.log('contentChildren-> ' + this.contentChildren.length));
}
}
bootstrap(ParentCmp, []);
child.ts
import {Component} from 'angular2/core';
@Component({
selector:'child',
template:`
<h5>child cmp</h5>
<ng-content></ng-content>
`
})
export class childcmp{
msg()
{
console.log('msg from child');
}
}
child1.tsこのセットアップに関連
import {Component} from 'angular2/core';
@Component({
selector:'child1',
template:`
<h5>child1 cmp</h5>
<ng-content></ng-content>
`
})
export class child1cmp{
msg()
{
console.log('msg from child1');
}
}
質問。
ここに私のコードをチェック - http://plnkr.co/edit/F2pJn1zxGFdFYzpeEwe1?p=preview
1)ParentComponent
は3人の子供(two child type
とone child1 type
)
<child></child>
<child></child>
<child1></child1>
は、どのように私は3人の子供のための3カウント得ることができたのか?
2)ViewChildren
とContentChildren
を使用するための論理的/実用的な方法は何ですか?(その使い方と方法はかなり混乱しています)。
がhttp://stackoverflow.com/questions/32681558/angular-2-0-whats-the-difference-between-viewquery-and-queryのDUPのように見えますか? –