formControl的ControlValueAccessor

formControl的ControlValueAccessor

本文介绍了子组件中具有多个formControl的ControlValueAccessor的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在子组件中有多个formcontrol,如何在子组件中应用验证器,因此原始表单将变得无效.最好使用ControlValueAccessor来实现它,但要从简单的@input表单组开始.

I have multiple formcontrols in the child component, how to apply validators in the child component, So that original form will become invalid. It would be ideal to implement it with ControlValueAccessor but want to start with simple @input form group.

@Component({
  selector: 'my-child',
  template: `

  <h1>Child</h1>
  <div [formGroup]="childForm">
    <input formControlName="firstName">
    <input formControlName="lastName">
  </div>
  `
})

export class Child {
  @Input()
  childForm: FormGroup;
}

http://plnkr.co/edit/K1xAak4tlUKtZmOV1CAQ

推荐答案

我不知道为什么这个问题被否决,但我认为这可能对其他人有帮助,所以我发布了答案.多次尝试绑定孩子的表单组后,我成功绑定了值

I don't know why the question was down voted, but I feel it may be helpful to other So I am posting the answer.After multiple attempts to bind child's formgroup I was able to successfully bind value

  @Component({
  selector: 'my-child',
  template: `

  <h1>Child</h1>
  <div [formGroup]="name">
    <input formControlName="firstName">
    <input formControlName="lastName">
  </div>
  `,
  providers: [
    {provide: NG_VALUE_ACCESSOR, useExisting: Child, multi: true}
  ]
})

export class Child implements ControlValueAccessor {
  name: FormGroup;
  constructor(fb: FormBuilder) {
    this.name = fb.group({
      firstName:[''],
      lastName: ['']
    });
  }

  writeValue(value: any) {
    if(value) {
        this.name.setValue(value);
    }
  }

  registerOnChange(fn: (value: any) => void) {
    this.name.valueChanges.subscribe(fn);
  }

  registerOnTouched() {}
}

http://plnkr.co/edit/ldhPf7LTFVtTFHe9zfAj?p=preview

这篇关于子组件中具有多个formControl的ControlValueAccessor的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-22 14:20