How can I create my own component for FormControls?

后端 未结 2 1889
后悔当初
后悔当初 2021-01-03 15:25

I would like to create a form and use a new, custom component for its controls. So I created a new component and included it into the parent form. But although the parent fo

相关标签:
2条回答
  • 2021-01-03 15:40

    You should also be passing the formGroup instance along with control name to your custom component. And then create a form control under that formGroup in custom component. Your custom component will create the control virtually under the same formGroup that you have provided.

    <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);
      }
    }
    

    With this your parent component can access all the form controls defined within their respective custom components.

    0 讨论(0)
  • 2021-01-03 16:00

    I played around with the accepted answer for a long time, and never had any luck.

    I had much better results implementing the ControlValueAccessor interface as shown here: https://alligator.io/angular/custom-form-control/

    It's actually pretty simple, I also rigged up an Example StackBlitz

    0 讨论(0)
提交回复
热议问题