Search code examples
angularangular-directive

In Angular, How can we detect if DOM element has ngModel associated with it?


I have an attribute directive that modifies the checked state of the host element. I'm using following code to do this:

constructor(private el: ElementRef, private model: NgModel) {}

//OnInit code

if ('ng-reflect-model' in this.el.nativeElement.attributes) { <-- Problem is here, this attribute is available for debug, i want to put some condition here
  this.model.viewToModelUpdate(modelValue);
  this.model.valueAccessor.writeValue(modelValue);
} else {
  this.el.nativeElement.checked = modelValue;
}

My problem is when the input has ngModel associated with it, I want to update the model if it is available otherwise update the checked state of native element.


Solution

  • One solution that i'm using presently is relying on this.model.valueAccessor property of NgModel class. If this attribute is absent then we can't access model value so no point in using it for update.

    So my updated code is:

    if (this.model.valueAccessor !== undefined && this.model.valueAccessor !== null) {
      this.model.viewToModelUpdate(modelValue);
      this.model.valueAccessor.writeValue(modelValue);
    } else {
      this.el.nativeElement.checked = modelValue;
    }
    

    This is based on https://angular.io/api/forms/NgControl#valueAccessor