2017-09-01 50 views
0

我想創建一個表單併爲其控件使用新的自定義組件。所以我創建了一個新組件並將其包含在父窗體中。但是,儘管父表單有一個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'指令的自定義組件,它需要應用像自定義組件,而不是在它裏面。 –

回答

1

你也應與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會比表格名稱更好的名稱和你的描述,這並不是說完全正確:?。?「你也應該路過的形式」的名字? –

相關問題