각도의 FormGroup 및 FormBuilder
내용의 테이블
FormGroup 소개
Many model controllers use the FromGroup to bind under a single form. angular FormGroup class is more useful when there are many fields of the form and need to tracks the value & validity of these fields.
FormGroup의 사용
Add the form modules metadata to the module class.
module.ts
// other imports ...
import { FormsModule ,ReactiveFormsModule } from '@angular/forms';
@NgModule({
imports: [
// other imports ...
ReactiveFormsModule,
FormsModule
],
})
export class AppModule { }
}
Create an instance of FormGroup in the component class then create a property named pocForm, and set the property to a new form group instance. To initialize the form group, provide the constructor with an object of named keys mapped to their control.
component.ts
import { FormBuilder , Validators } from '@angular/forms';
constructor(private fb: FormBuilder) { }
pocForm = this.fb.group({
firstName : ['' , [Validators.required]],
lastName : ['' , [Validators.required]],
nicNumber : ['' , [Validators.required]]
});
To bind form group to template need to use [formGroup] directive with form controllers.
component.html
<form [formGroup]="pocForm" (ngSubmit)="onSubmit(pocForm)">
<mat-form-field >
<mat-label>First Name</mat-label>
<input matInput formControlName ="firstName">
</mat-form-field>
<mat-form-field >
<mat-label>Last Name</mat-label>
<input matInput formControlName ="lastName">
</mat-form-field>
<mat-form-field >
<mat-label>Nic</mat-label>
<input matInput formControlName ="nicNumber">
</mat-form-field>
<button mat-flat-button [disabled]="pocForm.invalid"
type="submit" >Submit</button>
</form>
양식에 값 패치
patchValue() values are used to set values controllers in formGroup.
component.ts
patch(){
this.pocForm.patchValue({
firstName: 'dev'
})
}
값에 액세스
Using form controllers can access the form values in here show access the value of firstName.
component.ts
fValueName(){
this.pocForm.controls['firstName'].value;
}
필수 메시지 표시
There are many ways to display warning messages in angular. In here listen to the form controller status and display the error message.
component.ts
get f(){
return this.pocForm.controls;
}
component.html
<mat-form-field>
<mat-label>First Name</mat-label>
<input type="text" matInput formControlName="firstName">
<div class="errorMessage" *ngIf="f.firstName.invalid
&& (f.firstName.dirty || f.firstName.touched)">
<div *ngIf="f.firstName.errors?.required">
First Name Required
</div>
</div>
</mat-form-field>
에서 제출
To submit form details use ng event binding.
component.ts
onSubmit(form: any) {
if(this.pocForm.valid){
console.log('Your form data : ', form.value);
}
}
Reference
이 문제에 관하여(각도의 FormGroup 및 FormBuilder), 우리는 이곳에서 더 많은 자료를 발견하고 링크를 클릭하여 보았다 https://dev.to/darshana991/formgroup-in-angular-1n6l텍스트를 자유롭게 공유하거나 복사할 수 있습니다.하지만 이 문서의 URL은 참조 URL로 남겨 두십시오.
우수한 개발자 콘텐츠 발견에 전념 (Collection and Share based on the CC Protocol.)