【问题标题】:Detect internal change to @Input property angular 4检测 @Input 属性角度 4 的内部变化
【发布时间】:2018-12-22 10:40:03
【问题描述】:

我知道当组件的 @Input 属性来自其父组件时会触发 ngOnChanges。但是我如何检测 @Input 属性是否在其组件中发生更改。我一直无法找到一个好的答案。 谢谢

【问题讨论】:

    标签: angular ngonchanges


    【解决方案1】:

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

    这是一个演示此的示例组件:

    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 语句。

    【讨论】:

      【解决方案2】:

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

      【讨论】:

        【解决方案3】:

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

        @Input() yourInput: string;
        
        ngOnChanges(changes: SimpleChanges) {
            this.doSomething(changes.yourInput.currentValue);
            // You can also use yourInput.previousValue and 
        }
        

        【讨论】:

          猜你喜欢
          • 2019-10-04
          • 1970-01-01
          • 2018-09-04
          • 1970-01-01
          • 2020-04-11
          • 1970-01-01
          • 2021-06-17
          • 1970-01-01
          • 2021-08-07
          相关资源
          最近更新 更多