@ContentChildren && QueryList

Posted by Tim Lin on 2019-01-24

@ContentChildren 能取得多個 child content (由 ng-content 投射的內容)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
<!--app.component.ts-->

@Component({
selector: 'app-root',
template: `
<div>
<auth-form
(submitted)="createUser($event)">
<h3>Create account</h3>
<button type="submit">
Join us
</button>
</auth-form>
<auth-form (submitted)="loginUser($event)">
<h3>Login</h3>
<auth-remember (checked)="rememberUser($event)"></auth-remember>
<auth-remember (checked)="rememberUser($event)"></auth-remember>
<auth-remember (checked)="rememberUser($event)"></auth-remember>
<button type="submit">
Login
</button>
</auth-form>
</div>
`
})

由上方可以看到在 app.component.ts 裡面有三個 <auth-remember

auth-form.component.ts 做了 content projection, 如此做了三個

所以在 auth-form.component.ts 要改成

1
@ContentChildren(AuthRememberComponent) remember: QueryList<AuthRememberComponent>;

來取得 child content 的所有內容,並存到 QueryList

ngAfterContentInit() 內則是對 QueryList 跑一個 forEach的迴圈
只要有按下其中一個 checkbox 都會改變 this.showMessage 的值

1
2
3
4
5
6
7
ngAfterContentInit() {
if (this.remember) {
this.remember.forEach((item) => {
item.checked.subscribe((checked: boolean) => this.showMessage = checked);
});
}
}

Result

Reference