Angular2 child property change not firing update on bound property

后端 未结 1 914
温柔的废话
温柔的废话 2020-12-09 17:26

I have a simple custom directive with an input, that I\'m binding to in my component. But for whatever reason, the ngOnchanges() method doesn\'t fire when changing a child p

相关标签:
1条回答
  • 2020-12-09 17:55

    In fact, it's a normal behavior and Angular2 doesn't support deep comparison. It's only based on reference comparison. See this issue: https://github.com/angular/angular/issues/6458.

    That said they are some workarounds to notify the directive that some fields in an object were updated.

    • Referencing the directive from the component

      export class AppComponent {
        test: { one: string; } = { one: '1' }
        @ViewChild(MyDirective) viewChild:MyDirective;
      
        clicked() {
          this.test.one = '4';
          this.viewChild.testChanged(this.test);
        }
      }
      

      In this case, the testChanged method of the directive is called explicitly. See this plunkr: https://plnkr.co/edit/TvibzkWUKNxH6uGkL6mJ?p=preview.

    • Using an event within a service

      A dedicated service defines testChanged event

      export class ChangeService {
        testChanged: EventEmitter;
      
        constructor() {
          this.testChanged = new EventEmitter();
        }
      }
      

      The component uses a service to trigger the testChanged event:

      export class AppComponent {
        constructor(service:ChangeService) {
          this.service = service;
        }
      
        clicked() {
          this.test.one = '4';
          this.service.testChanged.emit(this.test);
        }
      }
      

      The directive subscribes to this testChanged event in order to be notified

      export class MyDirective implements OnChanges,OnInit {
        @Input()
        test: { one: string; } = { one: "" }
      
        constructor(service:ChangeService) {
          service.testChanged.subscribe(data => {
            console.log('test object updated!');
          });
        }
      }
      

    Hope it helps you, Thierry

    0 讨论(0)
提交回复
热议问题