【问题标题】:Cannot update attribute value in angular directive无法更新角度指令中的属性值
【发布时间】:2019-01-08 08:56:17
【问题描述】:

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

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 状态。

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

【问题讨论】:

  • ngOnInit 中,this.control.valueChanges.subscribe((value) =&gt; console.log(value))。请注意,当您的控件的组件被销毁时,您需要取消订阅。

标签: angular angular7


【解决方案1】:

如前所述,您需要订阅 FormControl 的 valueChanges。当你的指令被销毁时,请不要忘记取消订阅它。

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

【讨论】:

  • 谢谢。它工作正常。如何在 onsubmit 中检查脏数据?
  • FormControls 有一个属性dirty。由于您将 FormControl 作为 @Input 传递给您的指令,因此您可以从您的组件和指令中访问它。 ` if(control.dirty) { //你的代码在这里 }`
【解决方案2】:

无需使用 Input 属性绑定传递表单控件。使用 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

【讨论】:

  • 谢谢。它工作正常。如何在 onsubmit 中检查脏数据?
  • 是的。我需要在提交时抓住它
猜你喜欢
  • 2014-10-09
  • 2020-11-03
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-09-27
  • 2021-07-21
  • 2015-03-03
相关资源
最近更新 更多