繁体   English   中英

无法更新Angular指令中的属性值

[英]Cannot update attribute value in angular directive

我已经编写了用于显示错误类的属性指令。

import { Directive, ElementRef, Renderer, Input, HostBinding } from '@angular/core';
import { FormControl } from '@angular/forms';

@Directive({
  selector: "[appErrorClass]"
})
export class ErrorClasseDirective {
  @Input('control') control: FormControl;

  constructor(
    private el: ElementRef,
    private renderer: Renderer
    ) {
  }

  ngOnInit(): void {
    console.log(this.control)
  }
}

FormControl来自控制器,正在运行。 但是我无法在自定义指令中获取表单控件更新。 我已经通过了这样的控制。

<div appErrorClass [control]="userForm.get('email')">

但是,我无法在指令中获取更新的FormControl状态。

请帮助任何人解决此问题。 提前致谢。

正如已经告诉您的那样,您需要订阅FormControl的valueChanges。 当您的指令被销毁时,请不要忘记取消显示它。

这是一个工作示例: https : //stackblitz.com/edit/angular-mjz363

无需使用输入属性绑定来传递表单控件。 使用NgControl

所有控件基于FormControl的指令都可以扩展的基类。 它将FormControl对象绑定到DOM元素。

注入NgControl可以访问formControlValue

import { Directive,Input, HostBinding } from '@angular/core';
import { NgControl } from '@angular/forms';
@Directive({
  selector: '[appAppError]'
})
export class AppErrorDirective {
  constructor(private control: NgControl) { }
  ngOnInit() {
    this.control.statusChanges.subscribe((e) => {
      console.log({
        valid: this.control.valid,
        dirty: this.control.dirty,
        touched: this.control.touched
      });
    });
  }

}

示例: https//stackblitz.com/edit/ngcontrol-status-changes-d2mcsp

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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