将 formControlName 传递给 Angular 组件

Sun*_*Sun 5 angular-components angular angular-reactive-forms controlvalueaccessor

我有一个反应形式。设置与此类似:

myForm: FormGroup;

    this.myForm= new FormGroup({
        name: new FormControl("", [Validators.required, Validators.maxLength(15), Validators.pattern('...')]),
        ...
    });
Run Code Online (Sandbox Code Playgroud)

我在我的表单上使用它,如下所示:

  <input
    type="text"
    formControlName="name"
  />
  <div *ngIf="name.errors?.required">
      Name is required
  </div>
  <div *ngIf="name.errors?.maxlength">
      Name must be {{ name.errors.maxlength.requiredLength }} characters        
  </div>
  <div *ngIf="name.errors?.pattern">
      Name has invalid characters.
  </div>
Run Code Online (Sandbox Code Playgroud)

这只是我表格的精简版。我有多个输入,我不得不为每个输入创建错误 div。

所以为了解决这个问题,我尝试创建一个组件。该组件与上面的代码非常相似:

  <input
    type="text"
    [formControlName]="formControlName"
  />
  <div *ngIf="name.errors?.required">
      Name is required
  </div>
  etc...
Run Code Online (Sandbox Code Playgroud)

.ts 文件:

@Component({
  selector: 'app-text',
  templateUrl: './text.component.html'
})
export class TextComponent  {

  @Input() formControlName: FormControl;
}
Run Code Online (Sandbox Code Playgroud)

所以在我的表单上,我想使用这个组件如下:

<app-text [formControlName]="name"></app-text>
Run Code Online (Sandbox Code Playgroud)

但是我不能让它与 formControlName 属性一起使用。

这可能吗?

谢谢

我快到了。

我已经创建了这个 StackBlitz 来展示我的进步:

演示

现在只是在努力解决错误以及如何访问 formControl 以检查这些错误

sch*_*der 0

您需要将表单控件传递给输入元素,

  <input

    [value]="val"
    type="text"
    (input)="val=$event.target.value;onChange($event.target.value)"
    (blur)="onTouched()"
    [formControl]="control"

  >


  <span *ngIf="control && !control.valid && control.touched">
    <span class="error" *ngIf="control.errors['required']"> The field should not be empty</span>
    <span class="error" *ngIf="control.errors['email']"> The field should be an email 
    </span>
  </span>
Run Code Online (Sandbox Code Playgroud)

获取自定义组件中的控件作为输入,并据此显示错误。

import { Component, OnInit, forwardRef, Input, OnChanges } from '@angular/core';
import { FormControl, ControlValueAccessor, NG_VALUE_ACCESSOR, NG_VALIDATORS } from '@angular/forms';

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

  constructor() { }

  propagateChange:any = () => {};

   @Input() control: FormControl;
 @Input('messageValue') _messageValue = 'whateves';  

  get messageValue() {
    return this._messageValue;
  }

  set messageValue(val) {
    console.log('set messageValue', val)
    this._messageValue = val;
    this.propagateChange(val);
  }

hi(event) {
  console.log('hi');
  console.log(event)
  this.messageValue = event;
}
  ngOnInit() {
  }

  ngOnChanges(changes) {
    console.log('changes', changes);
    this.propagateChange(this.messageValue);
  }

    writeValue(value) {
      console.log('writeValue', value);
          if (value) {
            this.messageValue = value;
      }
    }


  registerOnChange(fn) {
    console.log('onChange')
    this.propagateChange = fn;
  }

  registerOnTouched() {}

}
Run Code Online (Sandbox Code Playgroud)