如何从父级设置角度自定义输入组件(控制值访问器)的值?

mx_*_*ode 5 angular

我们能够为复选框、文本输入等本机输入元素设置值(如果需要)。

它将是这样的:

<input type="text" [value]="customValue">
Run Code Online (Sandbox Code Playgroud)

通过这种方式,我们可以将自定义值绑定到本机输入元素。

如何使用使用控制值访问器实现的自定义输入元素获得类似的结果?

例如,考虑这个自定义输入组件:


@Component({
  selector: 'child-custom-input',
  templateUrl: './child-custom-input.component.html',
  styleUrls: [],
  providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => ChildCustomInputComponent),
      multi: true,
    },
  ],
})
export class ChildCustomInputComponent implements ControlValueAccessor {
  _value: boolean;

  onChanged: any = () => {};
  onTouched: any = () => {};

  constructor() {}

  writeValue(value: any) {
    this._value = value;
  }

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

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

  setValue(value) {
    this._value = value;
    this.onChanged(value);
    this.check.emit(value);
  }
Run Code Online (Sandbox Code Playgroud)

以下来自父组件:

// parent-component.html

<child-custom-input [value]="customInputValue"> </child-custom-input>
Run Code Online (Sandbox Code Playgroud)

我怎样才能达到这样的结果呢?

就像从父组件到自定义子输入组件设置默认/初始值一样。

// child-custom-input.component.html

<input type="text" placeholder="Input something..." (input)="setValue($event.target.value)">
Run Code Online (Sandbox Code Playgroud)

或者可以是类似复选框的东西。唯一需要做的就是将父组件的值设置到此自定义子输入组件。

// child-custom-input.component.html

<input type="checkbox" (input)="setValue($event.target.checked)">
Run Code Online (Sandbox Code Playgroud)

Jos*_*man 4

为此,您还需要在 ChildCustomInputComponent 中定义一个@Input() value: any属性以及适当的gettersetter 。

export class ChildCustomInputComponent implements ControlValueAccessor {
.
.
.

  //The internal data model
  private innerValue: any = '';

  //get accessor
  @Input()
  get value(): any {
    return this.innerValue;
  }

  //set accessor including call the onchange callback
  set value(v: any) {
    if (v !== this.innerValue) {
      this.innerValue = v;
      this.onChangeCallback(v);
    }
  }

}
Run Code Online (Sandbox Code Playgroud)

这样您应该能够使用 ChildCustomInputComponent 并从任何父组件定义其 value 属性,如下所示:

<custom-input name="myCustomComponent" [value]="'Any value here'"></custom-input>
Run Code Online (Sandbox Code Playgroud)

如需进一步说明,请检查以下工作示例: https ://plnkr.co/edit/zNOYwrLsszY54DDL