Angular组件的初始化顺序与HTML元素的顺序不一定一致。当使用*ngIf指令是,在满足条件时,组件可能不会立即初始化。这意味着,如果一个组件在另一个组件之前应该被初始化,但是与其相关的结构在HTML模板中定义在后面,那么它将在后面被初始化。
以下是一个示例代码:
@Component({
selector: 'app-parent',
template: `
`,
styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
showChild = true;
constructor() { }
ngOnInit(): void {
}
}
在这个例子中,我们有一个ParentComponent和ChildComponent。ParentComponent中有两个ChildComponent实例:一个在*ngIf中,一个没有。如果showChild为true,ngIf中的ChildComponent将被初始化,不管它在HTML模板中的位置如何。如果showChild为false,ChildComponent仍将在HTML模板中的后面被初始化。为了使ChildComponent在父组件中ngIf中的组件之前初始化,我们可以使用静态子代装饰器。
@ViewChildren(ChildComponent) childComponents: QueryList;
在ParentComponent类中添加这行代码,并在ngAfterViewInit中进行重新排序。ngAfterViewInit在所有静态子视图都被初始化后调用。
ngAfterViewInit() {
this.childComponents.changes.subscribe(change => {
this.childComponents.toArray().sort((a, b) => {
return a.id - b.id;
});
});
}
现在,ChildComponent将按照id的顺序进行排序,而不管它在HTML模板中的位置如何。