反应形式:子组件中父级的FormControl验证器

时间:2018-10-22 14:22:01

标签: angular angular5 angular6 angular-reactive-forms controlvalueaccessor

所有人

我使用Angular 6构建了我的反应式表单。

在这里,我使用验证器在ParentComponent中构建了表单:

@Component({
  selector: 'parent',
  template: '
  <form [formGroup]="form" (ngSubmit)="onSubmit()">
    <div formGroupName="address">
        <child formControlName="street"></child>
        <child formControlName="housenumber"></child>
        <child formControlName="city"></child>
    </div>
  </form>'
})

export class ParentComponent implements OnInit {

    public form: FormGroup;

  constructor(private formBuilder: FormBuilder) {
  }

  ngOnInit() {
    this.form = this.formBuilder.group({
      address: this.formBuilder.group({
        street: new FormControl(null,[Validators.minLength(1), Validators.maxLength(40), Validators.required]),
        housenumber: new FormControl(null,[Validators.pattern("[0-9]{7}", Validators.required]),
        city: new FormControl(null,[ Validators.required]),
      })
    });  
  }

  onSubmit(){
    log.console("submit");
  }
}

对于输入字段,我想创建一个ChildComponent来为用户提供更多信息,并且我没有多次使用相同的代码。

@Component({
  selector: 'child',
  template: '
  <label>I´m a label</label>
  <input [(ngModel)]="_model"></input>
  {{_model.errors}}
  ',
   providers: [
    {
      provide: NG_VALUE_ACCESSOR,
      useExisting: forwardRef(() => ChildComponent),
      multi: true
    }
  ]
})

export class ChildComponent implements ControlValueAccessor {

    _model;
    onChange: any = () => { };
  onTouched: any = () => { };

  constructor() {
  }

  get model() {
    return this._model;
  }

  set model(val) {
    this._model = val;
    this.onChange(val);
  }

  writeValue(value: any): void {
    if (value) {
      this._model = value;
    }
  }

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

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

  setDisabledState?(isDisabled: boolean): void {
    throw new Error('Method not implemented.');
  }
}

输入值已成功传输到父组件。 但是,如何从子级的父级检查FormControl的有效性?

0 个答案:

没有答案