2017-12-17 1 views
0

저는 Angular 5를 배우고 있으며 "반응 형"폼 모델로 작업하기 시작했습니다. 그러나 거의 모든 예제와 튜토리얼에서 하나의 템플릿으로 전체 양식을 작성해야합니다. 일반적으로 AngularJS 1.x에서는 각 필드를 자체 지시어에 저장 한 다음 서로 연결하여 중복을 줄이는 양식을 만듭니다.개개의 각도 5 반응성 폼 요소를 다시 사용

하나의 파일 만 사용하고 템플릿과 모든 유효성 검사를 포함하는 각도 5 반응 형 양식으로이 작업을 수행하는 방법이 있습니까? 폼 요소 HTML, 유효성 검사 메시지 등을 포함하는 구성 요소가있는 두 부분으로 구성하는 방법을 볼 수 있지만 전체 양식의 구성 요소에 FormControl을 만들어 기본값을 지정해야합니다. 유효성 검사.

어쩌면 이것은 매우 일반적 일 뿐이지 만 정확하게 찾지는 못한다.하지만 누군가가 패턴, 튜토리얼 또는 도움을 주면 나를 높이 평가할 것이다. 양식. 고맙습니다!

답변

0

누군가 다른 사람이이 문제를 겪는 경우 내가 찾을 수있는 가장 좋은 대답은 모범 사례가 아니더라도 최소한 다른 개발자가 사용하는 가장 좋은 대답은 부모 "기본 양식에 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> 
     ... 
관련 문제