Angular 何时使用*ngIf=";isProductSearchEmpty“;或[style.display]=";显示产品“;?
有时我不知道何时使用Angular 何时使用*ngIf=";isProductSearchEmpty“;或[style.display]=";显示产品“;?,angular,Angular,有时我不知道何时使用*ngIf=“isProductSearchEmpty”或[style.display]=“displayProduct” 未找到“{searchStr}}”。。 我可以选择使用: <div [style.display]="displayProduct"> <div class="not-found searchStr"> "{{searchStr}}" not found.. </div> <rb-catego
*ngIf=“isProductSearchEmpty”
或[style.display]=“displayProduct”
未找到“{searchStr}}”。。
我可以选择使用:
<div [style.display]="displayProduct">
<div class="not-found searchStr">
"{{searchStr}}" not found..
</div>
<rb-categories></rb-categories>
</div>
未找到“{searchStr}}”。。
在product-list.component.ts中,isProductSearchEmpty
为true或false,displayProduct
为none或block。*ngIf:
根据表达式的值有条件地包含模板
它将从DOM中添加和删除元素。因此,当使用*NGIF时,应该考虑模板渲染可能会改变其他元素。
此外,*ngIf
可用于显示具有“ngIf-then else”语法的整个模板。当应用于标记的“大”块或存在else-if条件时,它更常用
[style.display]
只会触发css属性“display”的更改。更重要的是更改元素的显示属性
通常使用
[hidden]
来代替*ngIf
,后者采用相反的逻辑,不会从DOM中删除元素。大多数情况下,您需要在组件视图中正确处理(添加或删除)子主机视图(组件)和嵌入视图时使用ngIf
。这意味着:
- 更新
和ViewChild
查询ViewChildren
- 触发Ngondestory
@Component({
selector: 'my-app',
queries: [],
template: `
<h2>Hello {{name}}</h2>
<div *ngIf="false">
<a-comp></a-comp>
</div>
`
})
export class AppComponent {
name = `Angular! v${VERSION.full}`;
@ViewChildren(AComponent) children;
ngAfterViewInit() {
console.log(this.children.length); // 0
}
}
现在长度是1
:
ngAfterViewInit() {
console.log(this.children.length); // 1
}
当a-comp
被隐藏并且现在认为它仍然存在时,ngondestory
也不会被触发
我想说的是,当使用它的元素不包含子组件或使用ViewContainerRef创建的嵌入式视图时,可以安全地使用[style.display]=“'none'”
template: `
<h2>Hello {{name}}</h2>
<div [style.display]="'none'">
<a-comp></a-comp>
</div>
`,
ngAfterViewInit() {
console.log(this.children.length); // 1
}