我创建了一个PopupService,如下所示:
export class PopupService {
popups: PopupComponent[] = [];
open(popup: PopupComponent) {
this.popups.forEach(popup => popup.active = false);
popup.active = true;
}
close(popup: PopupComponent) {
popup.active = false;
}
}
弹出窗口应该是QueryList而不是Array吗?
popups: QueryList<PopupComponent>;
PopupComponent如下:
export class PopupComponent implements OnInit {
@Input() active: boolean = false;
constructor(public popupService: PopupService) { }
ngOnInit() {
this.popupService.popups.push(this);
}
close() {
this.popupService.close(this);
}
toggle() {
if (this.active)
this.popupService.close(this);
else
this.popupService.open(this);
}
}
简短:对于您的用例,一个简单的数组就足够了
Long:你不应该在你的用例中使用QueryList<T>
有两个原因记录in the docs:
this.popupService.popups.push(this);
这样的东西。您可以通过调整服务的API来克服这个问题。ViewChildren
和ContentChildren
提供的参考,你不使用它。所以基本上,角度应该负责管理它的实例,而不是你。这是我回答的主要原因。