누군가 다른 사람이이 문제를 겪는 경우 내가 찾을 수있는 가장 좋은 대답은 모범 사례가 아니더라도 최소한 다른 개발자가 사용하는 가장 좋은 대답은 부모 "기본 양식에 FormGroup을 만드는 것입니다 "구성 요소를 만들고 FormGroup에 새 FormControl을 만들고 연결하십시오.
<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>
여기
부모의 성분이다 : 여기서
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;
}
}
가 열린 원소 성분의 템플릿이다 : 예를 들어, 여기에서 재사용 가능한 형태 제어 요소는 양식 (이미 작업중인 자습서의 일부 내장 양식 요소가 있으며 재사용 가능한 양식 요소 구성 요소는 하나뿐입니다)
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>
...