ngOnChanges没有被调用

时间:2018-08-13 21:25:05

标签: angular typescript

我正在更新组件属性,但是未调用ngOnChanges。请查看链接的StackBlitz,以查看问题重现以及到目前为止我尝试过的所有事情:

Demopage

编辑:正确的链接以查看代码

相关代码

ngOnInit() {
    const testButton1 = document.getElementById('test-button1');
    testButton1.addEventListener('click', function() {
      console.log('about to set this.value');
      console.log(this.value);
      this.value = 'value set by button 1';
    }.bind(this));
    const testButton2 = document.getElementById('test-button2');
    testButton2.addEventListener('click', this.testButtonCallback2(this), false);
    const testButton3 = document.getElementById('test-button3');
    testButton3.addEventListener('click', this.testButtonCallback3.bind(this), false);
  }

  ngOnChanges() {
    console.log('ngOnChanges was called');
  }

  testButtonCallback2(outerThis) {
    return function() {
      console.log('about to set this.value');
      console.log(outerThis.value);
      outerThis.value = 'value is set by callback2';
    }
  }

  testButtonCallback3() {
    console.log('about to set this.value');
    console.log(this.value);
    this.value = 'value is set by callback3';
    this.changeDetectorRef.detectChanges();
  }

1 个答案:

答案 0 :(得分:0)

看看官方的docs

  

每当它检测到对Angular的更改时,Angular就会调用其ngOnChanges()方法。   组件(或指令)的输入属性。

您的组件中没有任何inputs,因此将永远不会调用ngOnChanges

此外,您实际上应该使用Angular提供的方法。我只能建议您遵循tutorial。例如,您不应在模板中使用addEventListener添加事件监听器,而应在模板中添加(click)

<button (click)="testButtonCallback()">Test Button</button>
        ^^^^^^^^^^^^^^^^^^^^^^^^^^^^