代码之家  ›  专栏  ›  技术社区  ›  Lazloman

检测@input属性angle 4的内部变化

  •  2
  • Lazloman  · 技术社区  · 6 年前

    我知道ngonchanges是在components@input属性来自其父组件时触发的。但我如何检测@input属性是否在其组件中发生了更改。我一直找不到很好的答案。 谢谢

    3 回复  |  直到 6 年前
        1
  •  3
  •   Sajeetharan    6 年前

    为此,您可以使用 ngOnChanges() 旧答案中也提到的生命周期方法:

    @Input() yourInput: string;
    
    ngOnChanges(changes: SimpleChanges) {
        this.doSomething(changes.yourInput.currentValue);
        // You can also use yourInput.previousValue and 
    }
    
        2
  •  1
  •   Wand Maker    6 年前

    你可以定义 @Input() 在setter方法上,以便在为属性设置新值时可以执行其他操作。

    下面是一个示例组件,演示了这一点:

    import { Component, Input } from '@angular/core';
    
    @Component({
      selector: 'hello',
      template: `<h1 (click)="name = 'Bye'">{{name}}!</h1>`,
      styles: [`h1 { font-family: Lato; }`]
    })
    export class HelloComponent {
    
      private _name: string;
    
      get name() {
        console.log("Returning name", this._name);
        return this._name;
      }
    
      @Input() 
      set name(newName) {
        console.log("Setting new name", newName);
        this._name = newName;
      }
    }
    

    此组件在另一个组件中使用时,可以指定如下:

      <hello  [name]="'Hi'"></hello>  
    

    例如,初始值 Hi 是从外部/父组件设置的,单击文本时,值将更新为 Bye 组件内部。在这两种情况下,您将观察 console.log 浏览器控制台中的语句。

        3
  •  0
  •   ランス    6 年前

    您可以使用需要由父组件捕获的output()或事件发射器。