在自定义 Angular 组件中访问 FormControl

Access FormControl inside custom Angular Component

我正在创建一个自定义 angular 组件,它会在我的 FormControl(响应式表单)无效时显示错误工具提示。 但是我不知道如何访问自定义组件中的 FormControl 来检查它是否被标记为有效。

我想完成的事情

<div [formGroup]="form">
     <input formControlName="name" type="text" />
     <custom-validation-message formControlName="name">My special error message!</custom-validation-message>
  </div>

已经遇到过的东西

ERROR Error: No value accessor for form control with name: 'surveyType'

通过使用 NG_VALUE_ACCESSOR 实现 ControlValueAccessor 解决了这个问题,即使我不想改变值。我还添加了一个注入器来访问 NgControl。

import { Component, OnInit, Injector } from '@angular/core';
import { NgControl, ControlValueAccessor, NG_VALUE_ACCESSOR } from '@angular/forms';

@Component({
    selector: 'custom-validation-message',
    templateUrl: './validation-message.component.html',
    providers: [{
        provide: NG_VALUE_ACCESSOR, multi: true, useExisting: ValidationMessageComponent
    }]
})
export class ValidationMessageComponent implements ControlValueAccessor, OnInit {
    public formControl: any;

    constructor(private injector: Injector) {
        super();
    }

    public ngOnInit(): void {
        const model = this.injector.get(NgControl);
        this.formControl = model.control;
    }

    public writeValue(obj: any): void {
    }
    public registerOnChange(fn: any): void {
    }
    public registerOnTouched(fn: any): void {
    }
    public setDisabledState?(isDisabled: boolean): void {
    }
}

当前问题 model.control 未定义。检查模型后,我发现模型和空一样好,只有 _parent 是我的表单的完整表示。 model._parent.controls 确实包含我表单的所有控件。但是还是不知道当前的控件。

如果我理解正确,<custom-validation-message> 应该只显示反应式表单输入的验证错误。

ControlValueAccessor 用于创建自定义输入。您想要做的是创建一个简单的组件,并将抽象控件作为输入。该组件可能如下所示:

ts:

@Input() public control: AbstractControl;
...

有了这个,您可以访问自定义组件内部的 formControls 属性,例如 invalidtouchederrors
html:

<ng-container *ngIf="control?.invalid && control?.touched">
  <ul>
    <li class="validation-message" *ngFor="let error of control.errors">
      {{error}}
    </li>
  </ul>
</ng-container>

然后添加应该显示错误的控件作为输入

<custom-validation-message [control]="form.get('name')"></custom-validation-message>

没有检查你的方法。 CustomControlValueAccessor 应该只用于真正的表单控件。这是一种创造性的方法,它可能会以某种方式起作用,但我不会这样做。

除了注入之外,还有其他方法可以访问验证组件中的 FormControl

1) 定义没有 FormBuilderFormGroup 以便您可以直接访问表单控件:

  firstName: new FormControl('');
  lastName: new FormControl('');

  profileForm = new FormGroup({
    firstName,
    lastName
  });

然后在您的 html 中,您可以将表单控件传递给自定义验证消息:

<custom-validation-message [control]="firstName">My special error message!</custom-validation-message>

2) 尽管如此,还是使用 FormBuilder,但使用 getter 函数:

// component

get firstName() {
    return this.profileForm.get('firstName') as FormControl;
}
<custom-validation-message [control]="firstName">My special error message!</custom-validation-message>

3) 或如 Thomas Schneiter 所写:访问模板中的控件:

<form [formGroup]="form">
   <input formControlName="name" type="text" />
   <custom-validation-message [control]="form.get('firstName)">My special error message!</custom-validation-message>
</form>

正如我所理解的那样,您只想制作一个组件来显示表单控件验证消息,另一个答案解释了为什么 ControlValueAccessor 不是这里的情况,您只想将控件表单引用传递给组件然后检查验证状态,Thomas Schneiter 的回答是正确的,但我遇到了这种情况,很难通过 get 方法保持 refrance,有时我们处于子组和表单数组中,所以我的想法是只传递表单控件的名称作为字符串然后获取控件引用。

CustomValidationMessageComponent

@Component({
  selector: "custom-validation-message",
  templateUrl: "./custom-validation-message.component.html",
  styleUrls: ["./custom-validation-message.component.css"]
})
export class CustomValidationMessageComponent {
  @Input()
  public controlName: string;

  constructor(@Optional() private controlContainer: ControlContainer) {} 

  get form(): FormGroup {
    return this.controlContainer.control as FormGroup;
  }

  get control(): FormControl {
    return this.form.get(this.controlName) as FormControl;
  }
}

模板

<ng-container *ngIf="control && control?.invalid && control?.touched">
  <ul>
    <li *ngIf="control.hasError('required')">
      this is required field
    </li>
    <li *ngIf="control.hasError('pattern')">
      pattern is invalid 
    </li>
    <li *ngIf="control.hasError('maxlength')">
      the length is over the max limit
    </li>
     <!-- <li *ngFor="let err of control.errors | keyvalue">
       {{err.key}}
     </li> -->
  </ul>

</ng-container>

你可以像这样使用它

<form [formGroup]="form">
 <label>
   First Name <input type="text" formControlName="firstName" />
   <div>
       <custom-validation-message controlName="firstName"></custom-validation-message>
   </div>
 </label>

 ...

</form>

demo

you can check this angular library ngx-valdemort created by JB Nizet where it solve this problem perfectly .

这是访问自定义 FormControl 组件 (ControlValueAccessor) 的 FormControl 的方法。测试 Angular 8.

<my-text-input formControlName="name"></my-text-input>
@Component({
  selector: 'my-text-input',
  template: '<input
    type="text"
    [value]="value"
  />'
})
export class TextInputComponent implements AfterContentInit, ControlValueAccessor {

  @Input('value') value = '';

  // There are things missing here to correctly implement ControlValueAccessor, 
  // but it's all standard.

  constructor(@Optional() @Self() public ngControl: NgControl) {
    if (ngControl != null) {
      ngControl.valueAccessor = this;
    }
  }


  // It's important which lifecycle hook you try to access it.
  // I recommend AfterContentInit, control is already available and you can still
  // change things on template without getting 'change after checked' errors.
  ngAfterContentInit(): void {
    if (this.ngControl && this.ngControl.control) {
      // this.ngControl.control is component FormControl
    }
  }
}