onChanges与doCheck钩子

本文探讨Angular组件的onChanges和doCheck生命周期钩子。doCheck由于事件触发频繁,可能导致性能问题,建议谨慎使用。

app HTML

<div class="parent">
  <div>
    问候语:<input type = "text" [(ngModel)]="greeting">
  </div>
  <div>
    姓名: <input type = "text" [(ngModel)]="user.name">
  </div>
</div>
<app-child [greeting]="greeting" [user]="user "></app-child>

app TS

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  greeting = 'Hello';
  user: {name: string} = {name: 'Jenny'};

  // tslint:disable-next-line:use-lifecycle-interface
  ngOnInit(): void {
  }
}

child HTML

<div class="child">
  <h2>我是子组件</h2>
  <div>问候语:{{greeting}}</div>
  <div>姓名:{{user.name}}</div>
  <div>消息:<input [ngModel]="message"></div>
</div>

child TS

import {Component, DoCheck, Input, OnChanges, OnInit, SimpleChanges} from '@angular/core';

// tslint:disable-next-line:no-conflicting-lifecycle
@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit, OnChanges, DoCheck {

  @Input()
  greeting: string;

  @Input()
  user: { name: string };

  oldUsername: string;

  changeDetected = false;

  noChangeCount = 0;

  message = '初始化消息';

  constructor() {
  }

  ngOnChanges(changes: SimpleChanges): void {

        console.log(JSON.stringify(changes, null, 2));
    }

  ngOnInit(): void {
  }

  ngDoCheck(): void {
    if (this.user.name !== this.oldUsername){
      this.changeDetected = true;
      console.log('ngDoCheck:用户名发生了变化,由' + this.oldUsername + '变更为了' + this.user.name);
      this.oldUsername = this.user.name;
    }

    if (this.changeDetected){
      this.noChangeCount = 0;
    }else{
      this.noChangeCount = this.noChangeCount + 1;
      console.log('名称无变化时,ngDoCheck方法被调用了多少' + this.noChangeCount + '次');
    }
    this.changeDetected = false;
  }
}

其中doCheck方法,因为是事件触发,及时调整一下光标也能触发,会造成性能问题,慎用。

评论 1
成就一亿技术人!
拼手气红包6.0元
还能输入1000个字符
 
红包 添加红包
表情包 插入表情
 条评论被折叠 查看
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值