【问题标题】:In Angular, How can we detect if DOM element has ngModel associated with it?在 Angular 中,我们如何检测 DOM 元素是否具有关联的 ngModel?
【发布时间】:2020-09-20 18:17:08
【问题描述】:

我有一个属性指令可以修改宿主元素的选中状态。我正在使用以下代码来执行此操作:

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;
}

我的问题是当输入有 ngModel 与之关联时,如果模型可用,我想更新模型,否则更新本机元素的已检查状态。

【问题讨论】:

    标签: angular angular-directive


    【解决方案1】:

    我目前使用的一种解决方案是依赖于 NgModel 类的 this.model.valueAccessor 属性。如果此属性不存在,则我们无法访问模型值,因此没有必要使用它进行更新。

    所以我更新的代码是:

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

    这是基于https://angular.io/api/forms/NgControl#valueAccessor

    【讨论】:

      猜你喜欢
      • 2018-11-27
      • 1970-01-01
      • 2014-09-28
      • 2014-11-14
      • 1970-01-01
      • 2018-08-03
      • 2013-06-07
      • 2014-09-30
      相关资源
      最近更新 更多