angualr4生命週期鉤子

  1. 理解
    Angular提供了生命週期鉤子,把這些關鍵生命時刻暴露出來,賦予咱們在它們發生時採起行動的能力。能夠將鉤子函數理解爲在合適的時候作合適的事情。
  2. 鉤子函數
    ng4主要提供了8個鉤子函數:
    ngOnchangescss

    @input屬性(輸入屬性)發生變化時,會調用。非此屬性,不會調用。
       當輸入屬性爲對象時,當對象的屬性值發生變化時,不會調用,當對象的引用變化時會觸發。
       先於ngOnInit調用。

    ngOnInithtml

    只執行一次,dom操做可放在其中。(最經常使用)

    NgDocheckvue

    每次發生變動檢測時會被調用
       ngDoCheck() 是Angular中的變動檢測機制.它由 zone.js 來實現的.其行爲是隻要你的Angular中的某個組件發生異步事件.就會檢查整個組件樹,以保證組件屬性的變化或頁面的變化是同步的.因此 ngDoCheck() 的觸發至關頻繁的.而且是咱們沒法預料到的.也許咱們在頁面上的一個無心識操做,就會觸發幾個甚至幾十個的 ngDoCheck() 生命週期鉤子.

    ngAfterContentInitdom

    在組件內容初始化以後調用

    ngAfterContentChecked異步

    內容投影:父組件寫在子標籤之間的內容會被渲染到子模板的ng-content中去,相似vue的slot
       組件及子組件每次檢查內容時調用
       當父子組件都有該鉤子時,父組件先執行。

    ngAfterViewInt函數

    組件相應的視圖初始化以後調用

    ngAfterViewCheckedspa

    組件及子組件每次檢查視圖時調用
       當父子組件都有該鉤子時,子組件先執行。
       ngAfterViewChecked與ngAfterViewInt中不容許修改綁定的屬性(@input屬性),不然拋出異常

    ngOnDestorycode

    銷燬,事件解綁。

    3.執行順序
    父組件:component

組件模板
<div class="panel-body">
    <input type="text" [(ngModel)]="name">
    {{name}}
     <son [name]="name"></son>
</div>
組件
@Component({
  selector: 'father',
  templateUrl: './father.component.html',
  styleUrls: ['./father.component.scss']
})
export class FatherComponent implements OnInit {
  public name:string;
  constructor() { }
  ngOnInit() {
    console.log("父組件ngOninit");
  }
  ngOnchanges(){
    console.log("父組件ngonchanges");
  }
  ngDoCheck (){
    console.log("父組件ngDocheck")
  }
  ngAfterContentInit(){
    console.log("父組件ngAfterContentInit")
  }
  ngAfterContentChecked(){
    console.log("父組件ngAfterContentChecked")
  }
  ngAfterViewInit(){
    console.log("父組件ngAfterViewInit")
  }
  ngAfterViewChecked(){
    console.log("父組件ngAfterViewChecked")
  }
}

子組件htm

@Component({
  selector: 'son',
  templateUrl: './son.component.html',
  styleUrls: ['./son.component.scss']
})
export class SonComponent implements OnInit {
  @Input() name:string;
  constructor() { }

  ngOnInit() {
    console.log("子組件ngOninit");
  }
  ngOnChanges (){
    console.log("子組件ngonchanges");
  }
  ngDoCheck (){
    console.log("子組件ngDocheck")
  }
  ngAfterContentInit(){
    console.log("子組件ngAfterContentInit")
  }
  ngAfterContentChecked(){
    console.log("子組件ngAfterContentChecked")
  }
  ngAfterViewInit(){
    console.log("子組件ngAfterViewInit")
  }
  ngAfterViewChecked(){
    console.log("子組件ngAfterViewChecked")
  }
  
}

看打印結果:
圖片描述

當在父組件的input中輸入內容時,會打印以下結果:
圖片描述

看到有人說只有當使用內容投影時纔會調用ngAfterConentChecked,當上面的裏面的代碼很顯然是沒用ng-content的,不知道該怎麼解釋這個ngAfterConentChecked。

相關文章
相關標籤/搜索