Angular生命周期钩子ngOnChanges的使用 - 补充监听子组件

117 阅读1分钟

Angular生命周期钩子ngOnChanges

触发时机:

当被绑定的输入属性的值发生变化时调用,不过首次调用是会发生在ngOnInit()之前的。当然必须是父组件使子组件输入属性值变化时才会调用,子组件自己改变输入属性的值不会调用。 ngOnChanges()方法获取了一个对象,它可以同时观测多个绑定的属性值,它把每个发生变化的属性名都映射到了一个SimpleChange对象, 该对象中有属性的当前值和前一个值。 触发条件:@input属性(输入属性)发生变化时,会调用。非此属性,不会调用。当输入属性为对象时,当对象的属性值发生变化时,不会调用,当对象的引用变化时会触发。

源码

app.component.ts

import { Component } from '@angular/core';
 
@Component({
  selector: 'app-root',
  templateUrl: './app.component.html'
})
export class AppComponent {
  greeting: string = 'Hello';
 
  user: { name: string } = { name: 'Tom' };
}

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
 
import { AppComponent } from './app.component';
import { FormsModule } from '@angular/forms';
import { ChildComponent } from './components/child/child.component';
 
@NgModule({
  declarations: [AppComponent, ChildComponent],
  imports: [BrowserModule, FormsModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.html

<div style="background: lightcoral;padding: 10px;">
    <h3>我是父组件</h3>
    <div>
        问候语:<input type="text" [(ngModel)]="greeting">
    </div>
    <div>
        姓名:<input type="text" [(ngModel)]="user.name">
    </div>
</div>
<app-child [greeting]="greeting" [user]="user"></app-child>

child.component.ts

import { Component, Input, OnChanges, SimpleChanges } from '@angular/core';
 
@Component({
  selector: 'app-child',
  templateUrl: './child.component.html'
})
export class ChildComponent implements OnChanges {
  @Input()
  greeting: string;
  @Input()
  user: { name: string };
  message: string = '初始化消息';
  log: string = '';
 
  ngOnChanges(changes: SimpleChanges): void {
    console.log(JSON.stringify(changes, null, 2));
    this.log = JSON.stringify(changes, null, 2);
  }
}

child.component.html

<div style="background:silver;padding: 10px;">
    <h3>我是子组件</h3>
    <div>问候语:{{greeting}}</div>
    <div>姓名:{{user.name}}</div>
    <div>消息:<input [(ngModel)]="message"></div>
    <pre style="color: red;">log:{{log}}</pre>
</div>