【问题标题】:Angular 9 | ngModel Provider in Directive not working as expected角 9 |指令中的 ngModel Provider 未按预期工作
【发布时间】:2020-10-27 17:26:51
【问题描述】:

我有一个指令读取输入控件的脏状态并采取一些行动。

以下是指令的代码。

// our root app component
import { Directive, HostListener, Input } from '@angular/core';
import { NgModel, FormGroup } from '@angular/forms';

@Directive({
    selector: '[ngModel][appMarkAsDirty]',
    providers: [NgModel]
})
export class MarkAsDirtyDirective {
    @Input('appMarkAsDirty')
    parentFormGroup: FormGroup;

    constructor(private model: NgModel) { }

    @HostListener('ngModelChange', ['$event'])
    onInputChange($event) {
        console.log('this.model', this.model);
        if (this.model.dirty) {
            this.parentFormGroup.markAsDirty();
        }
    }
}

问题是,当用户在控件中键入时,指令中的 ngModel 引用不会更新。它始终保持在初始阶段,即 value 始终为 null,并且控件始终被触摸为 false 和肮脏的 false。

这在 Angular 8 之前工作正常。并且,在 Angular 9 中已停止工作。

stackblitz 的链接: https://stackblitz.com/edit/angular-ivy-yxbzny

提前致谢!

【问题讨论】:

标签: angular angular-directive angular-forms angular9 angular2-ngmodel


【解决方案1】:

我认为您必须从指令的声明中删除 providers 数组:

@Directive({
    selector: '[ngModel][appMarkAsDirty]',
    // providers: [NgModel]
})

这是因为如果你有 2 个指令 AB 并且它们被应用在同一个元素上,你可以注入,例如 AB

a.directive.ts

@Directive({
  selector: '[appA]'
})
export class ADirective {
  aDir = true

  constructor() { }

}

b.directive.ts

@Directive({
  selector: '[appB]'
})
export class BDirective {
  bDir = true

  // Assuming `A` and `B` are applied on the same element
  // Using `@Optional()` will not throw an error in case `A` is not applied
  constructor(@Optional() private a: ADirective) {
    console.log(this.a)
  }

}

ng-run demo

【讨论】:

  • 这已经用类似的指令回答了我的问题 - valueChanges 保持沉默并删除提供者:[NgModel] 已修复它,在升级到 Angular 9 后发生。
【解决方案2】:

@manish 我已经编辑了 stackblitz URL 请 cilck here

[

【讨论】:

  • 不,这不起作用,因为这些字段是可选的。所以,不需要验证。
  • 那么,dirty 指令将如何作用于可选字段?
  • 对于脏的,不需要任何验证。如果用户在该字段中输入任何内容,它就会起作用。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-07-20
  • 2021-02-15
  • 2021-05-16
  • 1970-01-01
相关资源
最近更新 更多