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
}