29

我想在 Angular 2+ 中创建一个带有 ControlValueAccessor 接口的自定义表单元素。这个元素将是一个<select>. 是否可以将 formControl 属性传播到包装元素?就我而言,验证状态不会传播到嵌套选择,如您在随附的屏幕截图中所见。

在此处输入图像描述

我的组件如下所示:

  const OPTIONS_VALUE_ACCESSOR: any = {
  multi: true,
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => OptionsComponent)
  };

  @Component({
  providers: [OPTIONS_VALUE_ACCESSOR], 
  selector: 'inf-select[name]',
  templateUrl: './options.component.html'
  })
  export class OptionsComponent implements ControlValueAccessor, OnInit {

  @Input() name: string;
  @Input() disabled = false;
  private propagateChange: Function;
  private onTouched: Function;

  private settingsService: SettingsService;
  selectedValue: any;

  constructor(settingsService: SettingsService) {
  this.settingsService = settingsService;
  }

  ngOnInit(): void {
  if (!this.name) {
  throw new Error('Option name is required. eg.: <options [name]="myOption"></options>>');
  }
  }

  writeValue(obj: any): void {
  this.selectedValue = obj;
  }

  registerOnChange(fn: any): void {
  this.propagateChange = fn;
  }

  registerOnTouched(fn: any): void {
  this.onTouched = fn;
  }

  setDisabledState(isDisabled: boolean): void {
  this.disabled = isDisabled;
  }
  }

这是我的组件模板:

<select class="form-control"
  [disabled]="disabled"
  [(ngModel)]="selectedValue"
  (ngModelChange)="propagateChange($event)">
  <option value="">Select an option</option>
  <option *ngFor="let option of settingsService.getOption(name)" [value]="option.description">
  {{option.description}}
  </option>
  </select>
4

4 回答 4

16

样品柱塞

我看到两个选项:

  1. 将错误从组件传播FormControl到值更改<select> FormControl<select> FormControl
  2. 将验证器从组件传播FormControl<select> FormControl

以下变量可用:

  • selectModelNgModel<select>
  • formControlFormControl作为参数接收的组件的

选项 1:传播错误

  ngAfterViewInit(): void {
    this.selectModel.control.valueChanges.subscribe(() => {
      this.selectModel.control.setErrors(this.formControl.errors);
    });
  }

选项 2:传播验证器

  ngAfterViewInit(): void {
    this.selectModel.control.setValidators(this.formControl.validator);
    this.selectModel.control.setAsyncValidators(this.formControl.asyncValidator);
  }

两者之间的区别在于传播错误意味着已经存在错误,而 seconds 选项涉及第二次执行验证器。其中一些,比如异步验证器,执行起来可能成本太高。

传播所有属性?

没有通用的解决方案来传播所有属性。各种属性由各种指令或其他方式设置,因此具有不同的生命周期,这意味着需要特定的处理。当前的解决方案涉及传播验证错误和验证器。那里有很多房产可供选择。

请注意,您可能会FormControl通过订阅FormControl.statusChanges(). 通过这种方式,您可以获得控件是VALID、还是(异步验证仍在运行)。INVALIDDISABLEDPENDING

验证如何在幕后工作?

在引擎盖下,验证器是使用指令应用的(检查源代码)。这些指令providers: [REQUIRED_VALIDATOR]意味着使用自己的分层注入器来注册该验证器实例。因此,根据应用于元素的属性,指令将在与目标元素关联的注入器上添加验证器实例。

接下来,这些验证器由NgModel和检索FormControlDirective

验证器和值访问器的检索方式如下:

  constructor(@Optional() @Host() parent: ControlContainer,
              @Optional() @Self() @Inject(NG_VALIDATORS) validators: Array<Validator|ValidatorFn>,
              @Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) asyncValidators: Array<AsyncValidator|AsyncValidatorFn>,
              @Optional() @Self() @Inject(NG_VALUE_ACCESSOR)

并分别:

  constructor(@Optional() @Self() @Inject(NG_VALIDATORS) validators: Array<Validator|ValidatorFn>,
              @Optional() @Self() @Inject(NG_ASYNC_VALIDATORS) asyncValidators: Array<AsyncValidator|AsyncValidatorFn>,
              @Optional() @Self() @Inject(NG_VALUE_ACCESSOR)
              valueAccessors: ControlValueAccessor[])

请注意,@Self()已使用,因此使用自己的注入器(应用指令的元素的)来获取依赖项。

NgModelFormControlDirective有一个FormControl实际更新值并执行验证器的实例。

因此,交互的重点是FormControl实例。

此外,所有验证器或值访问器都在应用它们的元素的注入器中注册。这意味着父级不应访问该注入器。因此,从当前组件访问由<select>.

选项 1 的示例代码(很容易被选项 2 替换)

以下示例有两个验证器:一个是必需的,另一个是强制选项匹配“选项 3”的模式。

柱塞

options.component.ts

import {AfterViewInit, Component, forwardRef, Input, OnInit, ViewChild} from '@angular/core';
import {ControlValueAccessor, FormControl, NG_VALUE_ACCESSOR, NgModel} from '@angular/forms';
import {SettingsService} from '../settings.service';

const OPTIONS_VALUE_ACCESSOR: any = {
  multi: true,
  provide: NG_VALUE_ACCESSOR,
  useExisting: forwardRef(() => OptionsComponent)
};

@Component({
  providers: [OPTIONS_VALUE_ACCESSOR],
  selector: 'inf-select[name]',
  templateUrl: './options.component.html',
  styleUrls: ['./options.component.scss']
})
export class OptionsComponent implements ControlValueAccessor, OnInit, AfterViewInit {

  @ViewChild('selectModel') selectModel: NgModel;
  @Input() formControl: FormControl;

  @Input() name: string;
  @Input() disabled = false;

  private propagateChange: Function;
  private onTouched: Function;

  private settingsService: SettingsService;

  selectedValue: any;

  constructor(settingsService: SettingsService) {
    this.settingsService = settingsService;
  }

  ngOnInit(): void {
    if (!this.name) {
      throw new Error('Option name is required. eg.: <options [name]="myOption"></options>>');
    }
  }

  ngAfterViewInit(): void {
    this.selectModel.control.valueChanges.subscribe(() => {
      this.selectModel.control.setErrors(this.formControl.errors);
    });
  }

  writeValue(obj: any): void {
    this.selectedValue = obj;
  }

  registerOnChange(fn: any): void {
    this.propagateChange = fn;
  }

  registerOnTouched(fn: any): void {
    this.onTouched = fn;
  }

  setDisabledState(isDisabled: boolean): void {
    this.disabled = isDisabled;
  }
}

options.component.html

<select #selectModel="ngModel"
        class="form-control"
        [disabled]="disabled"
        [(ngModel)]="selectedValue"
        (ngModelChange)="propagateChange($event)">
  <option value="">Select an option</option>
  <option *ngFor="let option of settingsService.getOption(name)" [value]="option.description">
    {{option.description}}
  </option>
</select>

options.component.scss

:host {
  display: inline-block;
  border: 5px solid transparent;

  &.ng-invalid {
    border-color: purple;
  }

  select {
    border: 5px solid transparent;

    &.ng-invalid {
      border-color: red;
    }
  }
}

用法

定义FormControl实例:

export class AppComponent implements OnInit {

  public control: FormControl;

  constructor() {
    this.control = new FormControl('', Validators.compose([Validators.pattern(/^option 3$/), Validators.required]));
  }
...

FormControl将实例绑定到组件:

<inf-select name="myName" [formControl]="control"></inf-select>

虚拟设置服务

/**
 * TODO remove this class, added just to make injection work
 */
export class SettingsService {

  public getOption(name: string): [{ description: string }] {
    return [
      { description: 'option 1' },
      { description: 'option 2' },
      { description: 'option 3' },
      { description: 'option 4' },
      { description: 'option 5' },
    ];
  }
}
于 2017-05-26T14:43:30.210 回答
5

在我看来,这是在ControlValueAccessor基于组件中访问 FormControl 的最简洁的解决方案。解决方案基于Angular Material 文档中提到的内容

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

  // Here is missing standard stuff to implement ControlValueAccessor interface

  constructor(@Optional() @Self() public ngControl: NgControl) {
    if (ngControl != null) {
      // Setting the value accessor directly (instead of using
      // the providers) to avoid running into a circular import.
      ngControl.valueAccessor = this;
    }
  }

    ngAfterContentInit(): void {
       const control = this.ngControl && this.ngControl.control;
       if (control) {
          // FormControl should be available here
       }
    }
}
于 2020-05-17T19:31:51.427 回答
2

下面是一个示例,展示了如何获取(和重用)底层 FormControl 和底层 ControlValueAccessor。

这在包装组件(如输入)时很有用,因为您可以重复使用 Angular 创建的现有 FormControl 和 ControlValueAccessor ,从而避免重新实现它。

@Component({
  selector: 'resettable-input',
  template: `
     <input type="text" [formControl]="control">
     <button (click)="clearInput()">clear</button>
  `,
  providers: [{
    provide: NG_VALUE_ACCESSOR,
    useExisting: ResettableInputComponent,
    multi: true
  }]
})
export class ResettableInputComponent implements ControlValueAccessor {

  @ViewChild(FormControlDirective, {static: true}) formControlDirective: FormControlDirective;
  @Input() formControl: FormControl;

  @Input() formControlName: string;

  // get hold of FormControl instance no matter formControl or formControlName is given.
  // If formControlName is given, then this.controlContainer.control is the parent FormGroup (or FormArray) instance.
  get control() {
    return this.formControl || this.controlContainer.control.get(this.formControlName);
  }

  constructor(private controlContainer: ControlContainer) { }

  clearInput() {
    this.control.setValue('');
  }

  registerOnTouched(fn: any): void {
    this.formControlDirective.valueAccessor.registerOnTouched(fn);
  }

  registerOnChange(fn: any): void {
    this.formControlDirective.valueAccessor.registerOnChange(fn);
  }

  writeValue(obj: any): void {
    this.formControlDirective.valueAccessor.writeValue(obj);
  }

  setDisabledState(isDisabled: boolean): void {
    this.formControlDirective.valueAccessor.setDisabledState(isDisabled);
  }
}
于 2020-10-23T04:51:03.903 回答
0

如果你实现了验证(Validator / NG_VALIDATORS),AbstractControl 很早就被传递到你的验证函数中。你可以把它藏起来。

  validate(c: AbstractControl): ValidationErrors {
    this.myControl = c;
于 2020-06-30T15:52:41.493 回答