angular – ngOnChanges在输入属性更改时不触发

前端之家收集整理的这篇文章主要介绍了angular – ngOnChanges在输入属性更改时不触发前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
你是否可以在angular2中改变组件属性时以编程方式触发角度变化检测?
@Component({
   selector: 'my-component',})
class MyComponent implements OnChanges {
   @Input() message: string;

   ngOnChanges(changeRecord) {
      for (var change in changeRecord) {
         console.log('changed: ' + change);
      }
   }

   doSomething() {
     // I want ngOnChanges to be called some time after I set the 
     // message. Currently it is only called if the host element
     // changes the value of [message] on the element.
     this.message = 'some important stuff';
   }
}
尝试手动调用更改检测或花费大量时间来解决此问题是过度的,为什么不创建一个函数来处理所需的变异并在ngOnChanges和doSomething中调用它?就像是:
@Component({
  selector: 'my-component',})
class MyComponent implements OnChanges {
  @Input() message: string;
  viewMessage: string;

  ngOnChanges(changes: { [propertyName: string]: SimpleChange }) {
    for (let propName in changes) {
      if (propName === 'message') {
        this.updateView(this.message);
      }
    }
  }

  doSomething() {
    this.viewMessage = 'some important stuff';
  }

  updateView(message: string) {
    this.viewMessage = message;
  }
}

因此,viewMessage将是您将使用的属性并控制模板.

原文链接:https://www.f2er.com/angularjs/141101.html

猜你在找的Angularjs相关文章