6 Angular頁面生命週期

1 代碼結構

 

 2 app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'ngPro7';

  show01 = true;
}
app.component.ts

3 app.component.html

<h1>Hello World!</h1>

<button (click)="show01 = !show01">切換顯示狀態</button>
<app-myc01 *ngIf="show01"></app-myc01>
app.component.html

4 myc01.component.ts

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

@Component({
  selector: 'app-myc01',
  templateUrl: './myc01.component.html',
  styleUrls: ['./myc01.component.css']
})
export class Myc01Component implements OnInit {
  names = ['劉備', '關於', '張飛'];
  constructor() {
    //構造方法
    console.log("contructor:構造方法,組件出生的第一時間觸發");
  }

  ngOnInit(): void {
    //init:初始化,類似於Vue中的mounted
    console.log('ngOnInit:組件中的內容開始初始化');

    //發送網絡請求
  }

  ngAfterContentInit(): void {
    //Called after ngOnInit when the component's or directive's content has been initialized.
    //Add 'implements AfterContentInit' to the class.
    console.log('ngAfterContentInit:組件中的數據初始化時觸發');
  }

  ngAfterViewInit(): void {
    //Called after ngAfterContentInit when the component's view has been initialized. Applies to components only.
    //Add 'implements AfterViewInit' to the class.
    console.log('ngAfterViewInit:組件上的UI界面上初始化時')
  }

  ngAfterContentChecked(): void {
    //Called after every check of the component's or directive's content.
    //Add 'implements AfterContentChecked' to the class.
    console.log('ngAfterContentChecked:組件上的數據發生變化時');
  }

  ngAfterViewChecked(): void {
    //Called after every check of the component's view. Applies to components only.
    //Add 'implements AfterViewChecked' to the class.
    console.log('ngAfterViewChecked:組件上的UI 隨着數據變化而更新')
  }
  ngOnDestroy(): void {
    //Called once, before the instance is destroyed.
    //Add 'implements OnDestroy' to the class.
    console.log('ngOnDestroy:組件銷燬時觸發');
  }
}
myc01.component.ts

5 myc01.component.html

<p>myc01 works!</p>

<ul>
    <li *ngFor="let item of names">{{item}}</li>
</ul>
<button (click)="names.push('趙雲')">新增數據</button>
myc01.component.html

6 運行效果

 

發表評論
所有評論
還沒有人評論,想成為第一個評論的人麼? 請在上方評論欄輸入並且點擊發布.
相關文章