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