angular学习(变化检测)

angular学习(OnChanges)

1.OnChanges

当组件的任何输入属性发生变化,组件生命周期提供的钩子ngOnChanges 可捕获变化的内容。

示例:

Parent组件是Child组件的父组件,变化检测从根组件开始,会比 Child更早执行变化检测,在执行变化检测时 Parent中的pa属性,会传递到 Child的输入属性param中。此时 Child组件检测到param属性发生变化,因此组件内的 p 元素内的文本值从空字符串 变成 param的值。

child.component.ts

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

@Component({
   
  selector: 'exe-child',
  // templateUrl: './child.component.html',
  template: `
    <p>{
    { param1 }}</p>
    <p>{
    { param2 }}</p>
    <button (click)="changeParam1()">change param1</button>
  `,
  styleUrls: ['./child.component.css']
})
export class ChildComponent implements OnInit {
   

  @Input() 
  param1: string;

  @Input()
  param2: string;

  ngOnChanges(changes: SimpleChange){
   
    console.log(changes);
  }

  //不会触发ngOnChanges钩子,但能改变param1的值
  changeParam1(){
   
    this.param1 = 'abc';
    console.log(this.param1);
  }

  constructor() {
    }

  ngOnInit() {
   
  }
}

parent.component.ts

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

@Component({
   
  selector: 'exe-parent',
  // templateUrl: './parent.component.html',
  template: `
    <exe-child [param1]="pa1" [param2]="pa2"></exe-child>
  `,
  styleUrls: ['./parent.component.css']
})
export class ParentComponent implements OnInit {
   

  pa1: string = 'aaa';
  pa2: string = 'bbb';

  constructor() {
    }

  ngOnInit() {
   
    // this.pa1 = '666';
  }

}

用ngOnChanges()捕获的变化内容如图:

  • 2
    点赞
  • 2
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值