誰かがこの問題を抱えている場合は、私が見つけたベストプラクティス(少なくともベストプラクティスではないにしても、少なくとも他の多くの開発者によって使用されています)は、親 "メインフォームそのFormGroupに新しいFormControlを作成してアタッチします。例えば、ここで再利用可能なフォームコントロールするための成分である:ここ
import {Component, OnInit, Input} from '@angular/core';
import {FormControl, FormGroup, Validators} from '@angular/forms';
@Component({
selector: 'app-project-length',
templateUrl: './project-length.component.html',
styleUrls: ['./project-length.component.css']
})
export class ProjectLengthComponent implements OnInit {
@Input() isFormSubmitted: boolean;
@Input() projectForm: FormGroup;
constructor() {
}
ngOnInit() {
this.projectForm.addControl('projectLength', new FormControl(0, [Validators.required, this.hasCorrectLength]));
}
hasCorrectLength(control: FormControl): {[s: string]: boolean} {
const length: number = control.value;
if (length < 2 || length > 10) {
return { 'incorrectLength' : true };
}
return null;
}
}
は、フォーム要素部品についての鋳型である:ここ
<div class="form-group" [formGroup]="projectForm">
<label for="project-length">project length</label>
<input
class="form-control"
type="number"
id="project-length"
placeholder="Enter project length"
formControlName="projectLength"
/>
<span class="help-block"
*ngIf="!projectForm.controls['projectLength'].valid && (projectForm.controls['projectLength'].touched || isFormSubmitted)">
please enter a project length between 2 and 9
</span>
は、親のコンポーネントでありますフォーム(すでに私が取り組んでいるチュートリアルのいくつかの組込みフォーム要素と、再利用可能なフォーム要素コンポーネントが1つしかありません):
import { Component, OnInit } from '@angular/core';
import {FormControl, FormGroup, Validators} from '@angular/forms';
import { Status} from '../shared/Status';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit{
projectForm: FormGroup;
statuses: Array<Status> = [
{id: 1, name: 'Critical'},
{id: 2, name: 'Stable'},
{id: 3, name: 'Finished'}
];
formSubmitted: boolean = false;
ngOnInit() {
this.projectForm = new FormGroup({
namey: new FormControl(null, [Validators.required, this.cannotBeTest1]),
email: new FormControl(null, [Validators.required, Validators.email]),
status: new FormControl('1')
});
}
onSubmit() {
console.log(this.projectForm);
this.formSubmitted = true;
if (this.projectForm.valid) {
console.log('Form data:');
console.log(this.projectForm);
}
}
cannotBeTest1(control: FormControl): {[s: string]: boolean} {
...
}
}
メインフォームコンポーネントのテンプレートの重要な部分は次のとおりです。
<div class="container">
<div class="row">
<div class="col-xs-12 col-sm-10 col-md-8 col-sm-offset-1 col-md-offset-2">
<form class="ui form-vertical" [formGroup]="projectForm" (ngSubmit)="onSubmit()">
...
<app-project-length [projectForm]="projectForm" [isFormSubmitted]="formSubmitted"></app-project-length>
...