Angular5 *ngIf 和 hidden 的区别
問(wèn)題
項(xiàng)目中遇到一個(gè)問(wèn)題,有一個(gè)過(guò)濾查詢(xún)的面板,需要通過(guò)一個(gè)展開(kāi)折疊的button,來(lái)控制它的show 和 hide。這個(gè)面板中,有一個(gè)Select 組件,一個(gè) input 查詢(xún)輸入框。
原來(lái)代碼是:
<div class="accordion-content" *ngIf="showFilter"><div class="pTop"><div app-choosen-select [options]="selectCompOptions" (selectedDataChange)="onFilterChange($event)" class="cpu-select"></div></div><div class="form-group"><input type="text" placeholder="查詢(xún)" [(ngModel)]="searchTxt" (ngModelChange)="searchNode()"></div> </div>然后發(fā)現(xiàn),每次點(diǎn)擊 toggle button,都會(huì)觸發(fā)一次onFilterChange()事件,因?yàn)?app-choosen-select 組件在初始化時(shí)會(huì)觸發(fā)傳入的 selectedDataChange 事件。從而影響到預(yù)期的結(jié)果。
解決方案
將 `*ngIf` 改成 `hidden`。 <div class="accordion-content" [hidden]="!showFilter"><div class="pTop"><div app-choosen-select [options]="selectCompOptions" (selectedDataChange)="onFilterChange($event)" class="cpu-select"></div></div><div class="form-group"><input type="text" placeholder="查詢(xún)" [(ngModel)]="searchTxt" (ngModelChange)="searchNode()"></div> </div>What is the difference between *ngIf and [hidden]?
參考:https://stackoverflow.com/questions/43034758/what-is-the-difference-between-ngif-and-hidden
ngIf is a structural directive, it creates/destroys content inside the DOM. The [hidden] statement just hides/shows the content with css, i.e. adding/removing display:none to the element's style.
也就是,*ngIf=true 時(shí),會(huì)重新創(chuàng)建其內(nèi)部的 DOM 元素包括子組件,同時(shí)如果設(shè)置了數(shù)據(jù)綁定、事件綁定,也會(huì)重新綁定;*ngIf=false 時(shí),會(huì)銷(xiāo)毀其內(nèi)部的DOM 元素和子組件,也會(huì)銷(xiāo)毀綁定的數(shù)據(jù)和綁定的事件。
但是,[hidden]=true,只是隱藏了DOM元素和子組件,并沒(méi)有重新初始化,綁定的數(shù)據(jù)和事件都還在的。
So [hidden] is better used when we want the show/hide status to change frequently, for example on a button click event, so we do not have to load the data every time the button is clicked, just changing its hidden attribute would be enough.
Note that the performance difference may not be visible with small data, only with larger objects.
所以,在這樣的toggle 某一個(gè)元素的情況下,使用[hidden] 比較好。
轉(zhuǎn)載于:https://www.cnblogs.com/liulei-cherry/p/10062680.html
創(chuàng)作挑戰(zhàn)賽新人創(chuàng)作獎(jiǎng)勵(lì)來(lái)咯,堅(jiān)持創(chuàng)作打卡瓜分現(xiàn)金大獎(jiǎng)總結(jié)
以上是生活随笔為你收集整理的Angular5 *ngIf 和 hidden 的区别的全部?jī)?nèi)容,希望文章能夠幫你解決所遇到的問(wèn)題。
- 上一篇: 一些IOS开发中的小技巧
- 下一篇: BZOJ 1101: [POI2007]