我有一个简单的自定义指令和一个输入,我绑定到我的组件中。但是无论出于什么原因,当更改input属性的子属性时,ngonchanges()方法都不会触发。
我的组件

import {Component} from 'angular2/core';
import {MyDirective} from './my.directive';

@Component({
    directives: [MyDirective],
    selector: 'my-component',
    templateUrl: 'Template.html'
})

export class MyComponent {
    test: { one: string; } = { one: "1" }

    constructor( ) {
        this.test.one = "2";
    }
    clicked() {
        console.log("clicked");
        var test2: { one: string; } = { one :"3" };
        this.test = test2; // THIS WORKS - because I'm changing the entire object
        this.test.one = "4"; //THIS DOES NOT WORK - ngOnChanges is NOT fired=
    }
}

我的指令。
import {Directive, Input} from 'angular2/core';
import {OnChanges} from 'angular2/core';

@Directive({
    selector: '[my-directive]',
    inputs: ['test']
})

export class MyDirective implements OnChanges {
    test: { one: string; } = { one: "" }

    constructor() { }

    ngOnChanges(value) {
        console.log(value);
    }
}

模板.html
<div (click)="clicked()"> Click to change </div>
<div my-directive [(test)]="test">

有人能告诉我为什么吗?

最佳答案

事实上,这是正常的行为,angular2不支持深入的比较。只是基于参考比较。请参阅本期:https://github.com/angular/angular/issues/6458
也就是说,它们是通知指令对象中的某些字段已更新的一些解决方法。
从组件引用指令

export class AppComponent {
  test: { one: string; } = { one: '1' }
  @ViewChild(MyDirective) viewChild:MyDirective;

  clicked() {
    this.test.one = '4';
    this.viewChild.testChanged(this.test);
  }
}

在这种情况下,显式调用指令的testchanged方法。看这张照片:https://plnkr.co/edit/TvibzkWUKNxH6uGkL6mJ?p=preview
在服务中使用事件
专用服务定义testChanged事件
export class ChangeService {
  testChanged: EventEmitter;

  constructor() {
    this.testChanged = new EventEmitter();
  }
}

组件使用服务触发testChanged事件:
export class AppComponent {
  constructor(service:ChangeService) {
    this.service = service;
  }

  clicked() {
    this.test.one = '4';
    this.service.testChanged.emit(this.test);
  }
}

指令订阅此testChanged事件以便得到通知
export class MyDirective implements OnChanges,OnInit {
  @Input()
  test: { one: string; } = { one: "" }

  constructor(service:ChangeService) {
    service.testChanged.subscribe(data => {
      console.log('test object updated!');
    });
  }
}

希望对你有帮助,
蒂埃里

10-07 21:04