Angular ts中监听变量

这边有个需求,需要监控某个@input的变量变化,突然忘记怎么监听变量了,查了下,记录

这边使用angluar/core中的OnChanges接口,然后实现 ngOnChanges方法,只要变量发生了变化,这里面都可以监听到,然后就可以监听你具体想监听的变量了

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

@Component({
  selector: 'app-your-component',
  template: `
    <p>{{ person.name }}, {{ person.age }}</p>
  `
})
export class YourComponent implements OnChanges {
  @Input() person: { name: string, age: number };

  ngOnChanges(changes: SimpleChanges): void {
    if (changes.person) {
      const newPerson = changes.person.currentValue;
      // 在这里执行你的逻辑
      this.print(newPerson);
    }
  }

  print(person: { name: string, age: number }) {
    console.log(`${person.name}, ${person.age}`);
  }
}

  • 3
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Angular ,你可以使用 `ngOnChanges` 生命周期钩子或 `Observable` 来监听变量数据的变化。 1. 使用 `ngOnChanges` 生命周期钩子: - 在组件类实现 `ngOnChanges` 方法,并接收一个 `SimpleChanges` 对象作为参数。 - 在 `ngOnChanges` 方法,你可以通过访问 `SimpleChanges` 对象获取到变化前后的值,并执行相应的逻辑。 下面是一个示例: ```typescript import { Component, Input, OnChanges, SimpleChanges } from '@angular/core'; @Component({ selector: 'app-my-component', template: ` <p>Previous Value: {{ previousValue }}</p> <p>Current Value: {{ currentValue }}</p> ` }) export class MyComponent implements OnChanges { @Input() myVariable: any; previousValue: any; currentValue: any; ngOnChanges(changes: SimpleChanges) { if (changes.myVariable) { this.previousValue = changes.myVariable.previousValue; this.currentValue = changes.myVariable.currentValue; // 执行其他逻辑... } } } ``` 在上面的示例,`myVariable` 是一个输入变量,当它的值发生变化时,`ngOnChanges` 方法会被调用,并且我们可以通过 `changes.myVariable` 获取到变化前后的值。 2. 使用 `Observable`: - 在组件定义一个 `Subject` 或 `BehaviorSubject` 对象来作为可观察对象。 - 在需要监听数据变化的地方,订阅这个可观察对象,并在回调函数执行相应的逻辑。 下面是一个示例: ```typescript import { Component } from '@angular/core'; import { Subject } from 'rxjs'; @Component({ selector: 'app-my-component', template: ` <p>Current Value: {{ currentValue }}</p> ` }) export class MyComponent { myVariable$ = new Subject<any>(); currentValue: any; constructor() { this.myVariable$.subscribe(value => { this.currentValue = value; // 执行其他逻辑... }); } updateValue(newValue: any) { this.myVariable$.next(newValue); } } ``` 在上面的示例,`myVariable$` 是一个 `Subject` 对象,我们可以在其他地方调用 `updateValue` 方法来更新变量的值。当值发生变化时,订阅 `myVariable$` 的回调函数会被触发,我们可以在其获取到最新的值并执行相应的逻辑。 这两种方法各有不同的应用场景,你可以根据实际需求选择合适的方式来监听变量数据的变化。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值