有时我会不知道何时使用*ngIf="isProductSearchEmpty"
或[style.display]="displayProduct"
。
<div *ngIf="isProductSearchEmpty">
<div class="not-found searchStr">
"{{searchStr}}" not found..
</div>
<rb-categories></rb-categories>
</div>
我可以选择使用:
<div [style.display]="displayProduct">
<div class="not-found searchStr">
"{{searchStr}}" not found..
</div>
<rb-categories></rb-categories>
</div>
在 product-list.component.ts 中,isProductSearchEmpty
为true或false,displayProduct
为none或block。
答案 0 :(得分:2)
大多数情况下,您会希望使用ngIf
,因为它在组件视图中正确处理(添加或删除)子主机视图(组件)和嵌入视图。这意味着:
ViewChild
和ViewChildren
查询ngOnDestroy
以下是一个例子:
@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
}
}
尽管display.none
根本没有渲染DOM节点,但是Angular仍在处理子元素:
template: `
<h2>Hello {{name}}</h2>
<div [style.display]="'none'">
<a-comp></a-comp>
</div>
`,
,长度现在为1
:
ngAfterViewInit() {
console.log(this.children.length); // 1
}
隐藏ngOnDestroy
时,a-comp
也不会触发[style.display]="'none'"
,现在认为它仍然存在。
我想说,当ViewContainerRef
使用的元素不包含使用{{1}}创建的子组件或嵌入视图时,可以安全地使用{{1}}。
答案 1 :(得分:1)
* ngIf:
有条件地包含基于表达式值的模板。
它将添加和删除DOM中的元素。所以当你使用* ngIf时,你应该考虑你的模板渲染可能会改变其他元素。
此外,*ngIf
可用于显示整个模板,其中包含&#39; ngIf -then else&#39;句法。当应用于“大”时,它会被更多地使用。标记块或当其他条件正在进行时。
[style.display]
只会触发css属性&#39;显示&#39;更改。更改元素的显示属性更多。
通常使用[hidden]
代替*ngIf
,它采用反向逻辑并且不会从DOM中删除元素。