angular 脏值检测基础流程
臟值檢測需要我們知道的
1.單項(xiàng)數(shù)據(jù)流,從根節(jié)點(diǎn)檢查到當(dāng)前頁面節(jié)點(diǎn)
?2.臟值檢測時(shí)候的聲明周期
?更新dom以后 臟值檢測需要走兩次。下面我們配置一個(gè)demo演示。
首先配置我們需要的demo
routing里面路徑配置
const routes: Routes = [{path: 'home',component: HomeContainerComponent,},{path: 'change-detection',pathMatch: 'full',component: ParentComponent} ];我們使用change-detection 路徑區(qū)做臟值檢測
需要兩個(gè)模塊component ----- parents child? 先看parent.htm結(jié)構(gòu)
<p>{{ title }}parent works!</p> <app-child [title]="'Hello'"></app-child> <br /> <button (click)="handleClick()">觸發(fā)子視圖臟值檢測</button>再看child.html結(jié)構(gòu) 臟值檢測使用textContent綁定屬性 進(jìn)行測試。
<span [textContent]="title"></span> <!--如果不使用綁定,采用直接寫 DOM 的形式可以解決臟值檢測無限循環(huán)的帶來的性能問題<span #timeRef></span> --> <span [textContent]="time | date: 'HH:mm:ss:SSS'"></span> <p>child works!</p> <button (click)="handleClick()">觸發(fā)臟值檢測</button>進(jìn)入頁面change-detection 驗(yàn)證臟值檢測的流程。打開core.js 搜索function checkandupdateView函數(shù)增加斷點(diǎn)。 右下加可以關(guān)注component 從根節(jié)點(diǎn)一直到child節(jié)點(diǎn)?
child.js中
export class ChildComponent implements OnInit, AfterViewChecked {_title = 'hi';@Input()public get title(): string {console.log('子組件臟值檢測');return this._title;}public set title(v: string) {this._title = v;} }?
?顯示出來結(jié)果。
再來,關(guān)注這個(gè)函數(shù),打斷點(diǎn)
?
可以看到做了舊值和新值得比較,如果相等就放行。也就是說我們不能在?AfterViewChecked中修改title不然回一直死循環(huán)切報(bào)錯(cuò)??梢钥吹疆?dāng)前臟值檢測console.log輸出兩遍
?例如,我們繼續(xù)加入這塊代碼。之前說過臟值檢測這塊會(huì)走兩遍。那么我們這時(shí)候賦值,改變原有值,就會(huì)一直死循環(huán)。
ngAfterViewChecked(): void {// 在此處會(huì)拋出異常,不要在 ngAfterViewChecked// 或者 ngAfterViewInit 中去改變屬性值this.title = 'hello';}結(jié)果如下:
?
?通過一個(gè)demo來理解臟值檢測的基本流程,主要是最上方兩張圖。1.從根節(jié)點(diǎn)開始檢查。2.更新視圖的時(shí)候ngAfterViewChecked 還有ngAfterViewInit? 會(huì)走兩次 所以不要在這個(gè)時(shí)候改變值。
?
?
總結(jié)
以上是生活随笔為你收集整理的angular 脏值检测基础流程的全部內(nèi)容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: Windows Driver Devel
- 下一篇: 安装nginx-kafka插件ngx_k