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

问题描述:

我想创建一个表单并为其控件使用新的自定义组件。所以我创建了一个新组件并将其包含在父窗体中。但是,尽管父表单有一个formGroup,但Angular抱怨说没有。如何为FormControls创建我自己的组件?

错误:

Error: formControlName must be used with a parent formGroup directive. You'll want to add a formGroup directive and pass it an existing FormGroup instance (you can create one in your class).

母体形式有:

<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

这是否帮助? https://blog.thoughtram.io/angular/2016/07/27/custom-form-controls-in-angular-2.html – Thibs

+0

你需要克里特不'formControlName'指令的自定义组件,它需要应用像自定义组件 AVA外形控制>,而不是在它里面。 –

你也应与control name沿着通过formGroup实例您custom component。然后在自定义组件中创建一个form control下的formGroup。您的自定义组件将在您提供的相同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

如果窗体名称是字符串,为什么会它有方法的AddControl –

+0

@LynHeadley是的,你是正确的它是FormGroup更新 –

+0

所以formGroup会比表格名称更好的名称和你的描述,这并不是说完全正确:?。?“你也应该路过的形式”的名字? –