简体   繁体   中英

Angular: Injecting NgControl While Monitoring Changes

Given I have a directive that injects NgControl :

export class MyFormDirective {
  constructor(@Self() private ngControl: NgControl) {
    this.ngControl.valueChanges.subscribe(val => {
     // Do stuff
    });
  }

Used like so:

<input type="text" [formControl]="sampleControl" appMyFormDirective />

Is there a way for me to handle the situation where sampleControl is updated?

this.sampleControl = new FormControl(); // this will break the directive subscription

I have a component that potentially has multiple forms bound to it over its lifetime, which stops my directive from working. I can force everything to re-render by using *ngFor over *ngIf , but since the form directives themselves seem to be handling the change ok, I'd rather just fix the issue in my directive if possible.

Since I couldn't find any better solution, here is what worked for me:

I've added an input to my directive:

@Input()
formControl?: AbstractControl;

and implemented OnChanges interface. This way if when the formControl reference is updated, the ngOnChanges callback is triggered and I can react to it.

I couldn't find any way to handle it by just using the injected ngControl .

Another approach (perhaps even better) is to implement DoCheck interface and use it like this:

  formControl: AbstractControl|null = null; // class field

  ngDoCheck(): void {
    if (this.formControl !== this.ngControl.control) {
      this.formControl = this.ngControl.control;
      this.doStuff();
    }
  }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM