首页 文章

如何为FormControls创建自己的组件?

提问于
浏览
1

我想创建一个表单并为其控件使用新的自定义组件 . 所以我创建了一个新组件并将其包含在父表单中 . 但是虽然父表单有一个formGroup,但Angular抱怨说它没有 .

错误:

错误:formControlName必须与父formGroup指令一起使用 . 您将要添加formGroup指令并将其传递给现有的FormGroup实例(您可以在类中创建一个) .

父表格有:

<form [formGroup]="learningObjectForm" (ngSubmit)="onSubmit()" novalidate>
  <div>
    <button type="submit"
            [disabled]="learningObjectForm.pristine">Save</button>
  </div>

  <ava-form-control [label]="'Resource'"></ava-form-control>

</form>

在.ts中:

constructor(private fb: FormBuilder) {
    this.createForm();
  }

  createForm() {
    this.learningObjectForm = this.fb.group({
      text: '',
    });
  }

在我的自定义组件中

import { Component, Input, OnInit }       from '@angular/core';

@Component({
  selector: 'ava-form-control',
  template: `  <div>
    <label>{{label}} :</label>
    <input formControlName="{{name}}">
  </div>
`
})
export class FormControlComponent implements OnInit {

  @Input() label: string;
  @Input() name: string;

  constructor() {}

  ngOnInit() {
    if (this.name === undefined) {
      // turns 'The Label' into 'theLabel'
      this.name = this.label[0].toLowerCase().concat(this.label.slice(1));
      this.name = this.name.split(' ').join('');
      console.log(this.label, this.name);
    }
  }
}

2 回答

  • 2

    您还应该将 formGroup 实例和 control name 一起传递给 custom component . 然后在自定义组件中的 formGroup 下创建一个 form control . 您的自定义组件将在您提供的同一formGroup下虚拟创建控件 .

    <form [formGroup]="learningObjectForm" (ngSubmit)="onSubmit()" novalidate>
      <div>
        <button type="submit"
                [disabled]="learningObjectForm.pristine">Save</button>
      </div>
    
      <ava-form-control [label]="'Resource'" [formGroup]="learningObjectForm" [controlName]="'mycontrol'"></ava-form-control>
    
    </form>
    

    custom.component.ts

    import { Component, Input, OnInit }       from '@angular/core';
    
    @Component({
      selector: 'ava-form-control',
      template: `  <div>
        <label>{{label}} :</label>
        <input [formControl]="formGroup.controls[controlName]>
      </div>
    `
    })
    
    export class FormControlComponent implements OnInit {
    
      @Input() label: string;
      @Input() formGroup: FormGroup;
      @Input() controlName: string;
    
      constructor() {}
    
      ngOnInit() {
        let control: FormControl = new FormControl('', Validators.required);
        this.formGroup.addControl(this.controlName, control);
      }
    }
    

    有了这个,您的父组件可以访问其各自自定义组件中定义的所有表单控件 .

  • 0

    我玩了很长一段时间接受了接受的答案,从来没有运气 .

    我有更好的结果实现ControlValueAccessor接口,如下所示:https://alligator.io/angular/custom-form-control/

    它实际上很简单,我也装了一个Example StackBlitz

相关问题