角 9 |指令中的 ngModel Provider 未按预期工作 [英] Angular 9 | ngModel Provider in Directive not working as expected

查看:19
本文介绍了角 9 |指令中的 ngModel Provider 未按预期工作的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

I have one directive which reads the dirty state of the input control and takes some action.

以下是指令的代码.

// 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 引用不会更新.它始终保持在其初始阶段,即值始终为空,并且控件始终被触摸为虚假和肮脏的虚假.

The issue is, ngModel reference in the directive doesn't get updated when user types in the control. It Always remains at its initial stage i.e. value is always null and control is always touched as false and dirty as false.

这在 Angular 8 之前一直运行良好.而且,在 Angular 9 中已经停止工作.

This is working fine till Angular 8. And, has stopped working in Angular 9.

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

Link to stackblitz: https://stackblitz.com/edit/angular-ivy-yxbzny

提前致谢!

推荐答案

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

I think you'll have to remove the providers array from the directive's declaration:

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

那是因为如果你有 2 个指令,AB 并且它们被应用在同一个元素上,你可以注入,例如,A<B 中的/code>:

That is because if you have 2 directives, A and B and they are applied on the same element, you can inject, for instance, A in B:

@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 演示

这篇关于角 9 |指令中的 ngModel Provider 未按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆