我有一个卡片对象的集合
...
cards: Card[];
...
ngOnInit() {
this.cardService.getCards.subscribe(r => { this.cards = r; });
}
我在模板中添加子卡片组件,如下所示
<div id="cards-container">
<app-card *ngFor="let card of cards" [name]="card.name"></app-card>
</div>
Card组件具有一个名称和一些依赖于active属性的样式,该属性可通过单击组件来切换
@Component({
selector: 'app-card',
templateUrl: './card.component.html',
'styleUrls: ['./card.component.scss']
})
export class CardComponent {
private _name = '';
private _active = false;
// getters/setters
...
onClick(e) {
this.active = !this.active;
}
}
card.component.html
<div [ngClass]="{'card': true, 'active': _active}"
(click)="onClick($event)">
{{name}}
</div>
所有这些都运行得很好。
问题:在父组件中,我需要迭代使用*ngFor="let card of cards"
添加的所有卡片组件,并将它们都设置为活动或不活动,但我不知道如何做到这一点。
我尝试了什么:我尝试使用@ViewChildren()
,但QueryList的toArray()
方法总是给我一个空数组。从ViewChildren documentation中的有限示例中,我不是百分之百清楚是否需要在父组件中添加额外的指令,或者示例中的指令是否只是用于演示。所以我尝试的内容是
@ViewChildren(CardComponent) cardList: QueryList<CardComponent>;
我也尝试过使用类似于this answer的东西来使用ViewContainerRef,但我无法让它工作,这似乎并没有将我带向正确的方向。我也看过the documentation for ComponentRef,但我不知道这是否能帮助我解决我的问题。
任何给我指出正确方向的建议都将不胜感激。
更新
我在card组件中的活动setter如下所示
@Input()
set active(active: boolean) {
this._active = active;
}
我需要能够在任何时候为所有卡片更改此选项,换句话说,“选择/取消选择全部”选项。
已解决!
通过使用suggestion from @Tim Klein,我订阅了QueryList的changes
,并且能够将我的组件放在一个数组中,当QueryList发生变化时,我会更新该数组。现在我只需迭代组件数组并调用我的active
设置器。
cards: CardComponent[];
@ViewChildren(CardComponent) cardList: QueryList<CardComponent>;
...
ngAfterViewInit(): void {
this.cards = this.cardList.toArray(); // empty array but that's okay
this.cardList.changes.subscribe((r) => {
this.cards = this.cardList.toArray(); // we get all the cards as soon as they're available
});
}
发布于 2019-04-16 03:01:10
我认为您可能面临的问题是,一旦调用了afterViewInit
生命周期事件,您的动态组件仍然没有加载。因此,如果您在afterViewInit
中调用cardList.toArray()
,它将返回一个空列表,因为您的组件尚未添加到父组件的视图中。
您应该尝试订阅changes
observable (就像在this example中一样),并在回调中调用您的逻辑来更改子组件的状态。
更新
另一种选择是简单地为您的子组件提供另一个输入,该输入可以接受活动状态的布尔值。
然后,在设置Card
对象列表时,只需遍历并更改一些active
属性。只需在父组件模板中设置该属性和name
即可。
https://stackoverflow.com/questions/55695537
复制相似问题