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; }
3 app.component.html
<h1>Hello World!</h1> <button (click)="show01 = !show01">切换显示状态</button> <app-myc01 *ngIf="show01"></app-myc01>
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:组件销毁时触发'); } }
5 myc01.component.html
<p>myc01 works!</p> <ul> <li *ngFor="let item of names">{{item}}</li> </ul> <button (click)="names.push('赵云')">新增数据</button>
6 运行效果