带有错误消息的角度自定义表单输入

时间:2017-10-25 22:34:53

标签: javascript angular angular-forms

我想创建一个自定义表单输入,它只是普通输入的包装,并在formControl无效时显示错误消息。

所以我创建了一个实现ControlValueAccessor的组件,但现在我想显示错误消息,我意识到我没有FormControl,因此我需要将其作为@Input()传递。问题是......如果我可以将FormControl作为输入传递,为什么首先实现ControlValueAccessor?我很困惑。

HTML

<input  
  [placeholder]="placeholder"
  [type]="type" 
  [(ngModel)]="value"
  (keyup)="onChange()"
  (change)="onChange()" 
  (blur)="onTouched()" 
  [disabled]="disabled"/>

TS

@Component({
  selector: 'input-app',
  templateUrl: './input.component.html',
  providers: [
    { 
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => InputComponent),
      multi: true
    }
  ]
})
export class InputComponent implements ControlValueAccessor {

  @Input() type = 'text';
  @Input() placeholder = 'placeholder';
  @Input() errorMsg = '';
  value: string;
  disabled: boolean;
  private onChangeFn;
  private onTouchedFn;

  writeValue(val: string | number): void {
    this.value = val;
  }

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

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

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

  onChange(){
    this.onChangeFn(this.value);
  }

  onTouched(){
    this.onTouchedFn();
  }

}

0 个答案:

没有答案