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 运行效果

 

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