2017-07-29 15 views
2

有時我會做不是知道何時使用*ngIf="isProductSearchEmpty"[style.display]="displayProduct"您何時使用* 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> 

產品list.component.tsisProductSearchEmpty是真或假,displayProduct是沒有或塊。

回答

1

* ngIf:

有條件包括基於表達式的值的模板。

它會添加和刪除DOM中的元素。所以,當你使用* ng時,如果你應該考慮你的模板渲染可能會改變其他元素。 此外,*ngIf可以用來顯示一個完整的模板'ngIf -then else'語法。當應用於「大」標記塊時或者在條件正在進行時還有其他情況時,它會更加有用。

[style.display]只會觸發css屬性的「顯示」更改。這更多的是改變元素的顯示屬性。

經常使用[hidden]代替*ngIf,它採用反向邏輯並且不會從DOM中刪除元素。

3

大多數情況下,您會希望使用ngIf,因爲它正確地處理(添加或刪除)組件視圖中的子主機視圖(組件)和嵌入的視圖。這意味着:

  • 更新ViewChildViewChildren查詢
  • 觸發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創建的子組件或嵌入視圖。