簡體   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