簡體   English   中英

啟用div的更好方法

[英]Better way of enabling a div

我有兩個div,我必須根據收到的響應將其隱藏或顯示。 例如說

<div *ngIf= "field1 != null ">
  <p>field1 </p>
</div>
<div *ngIf= "field2 != null ">
  <p>field2 </p>
</div>

我的回應是

{
  " field1" : "Field1" ,
  " field2" : null ,

}

根據我的回答,只有我的field1是可見的。 我想知道有沒有更好的方法可以做到這一點。 萬一將來如果響應發生更改,無論引用到哪里,我都必須更改HTML。 我可以概括一下嗎?

組件:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent implements OnInit {
  response = {
    "field1": 1, 
    "field2":null, 
    "field3": "foo", 
    "field4": 42,
    "field5": undefined
  };
  responseProperties = [];
  ngOnInit() {
      //In here for demo purpose.
      //Put this code after getting the "response"
      for(let propertyName in this.response) {
           let value:any = this.response[propertyName];
           if(value || value === false)
           this.responseProperties.push({propertyName, value});
      }
  }
}

關聯的模板:

<div *ngFor="let p of responseProperties">
  <p>{{p.propertyName}}: {{p.value}}</p>
</div>

結果:

欄位1:1

field3:foo

欄位4:42

如果您寫*ngIf="field1"會更好,因為如果undefined ,null, 0則為undefined ,null, 0將被視為false (數字類型為0)。 否則,如果包含任何內容,將被視為true

如果只想顯示一個存在的字段,那么* ngIf語句將正常工作。 將綁定添加到<p>標記將確保字段屬性隨所做的任何更改而動態更新。

像這樣:

<div *ngIf="field1 !== null ">

  <p>{{field1}}</p>

</div>

<div *ngIf="field2 !== null ">

  <p>{{field2}}</p>

</div>

這將保持

  • 如果該字段存在,將顯示相應的<div>
  • div的內容將綁定到相應字段變量的值,這意味着如果響應發生更改,則無需更新html。

    Angular使用其更改檢測算法不斷更新html中的* ngIf和{{}}標簽。 如果您想進一步了解它的工作原理,請參閱以下文章,說明其工作方式: https : //blog.thoughtram.io/angular/2016/02/22/angular-2-change-detection- explained.html

  • 暫無
    暫無

    聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

     
    粵ICP備18138465號  © 2020-2024 STACKOOM.COM