ติดตั้ง @rxweb/reactive-form-validators
$ npm install @rxweb/reactive-form-validators
/** app.module.ts */
import { RxReactiveFormsModule } from '@rxweb/reactive-form-validators';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
RxReactiveFormsModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
สร้าง job.model.ts
สร้าง models เพื่อใช้การทำ validate forms
/** models/job.model.ts*/
import { required } from "@rxweb/reactive-form-validators";
export class JobModel {
@required()
jobName: string;
...
}
สร้าง user.model.ts
สร้าง models เพื่อใช้การทำ validate forms
/** models/user.model.ts*/
import { required, requiredTrue } from "@rxweb/reactive-form-validators";
export class JobModel {
@required()
jobName: string;
@requiredTrue()
jobValue: boolean;
}
Config validationMessage & ผูก models
/** app.component.ts */
import { ReactiveFormConfig } from '@rxweb/reactive-form-validators';
...
export class AppComponent implements OnInit {
myForm!: FormGroup;
constructor(private formBuilder: RxFormBuilder) { }
...
ngOnInit(): void {
ReactiveFormConfig.set({
validationMessage: {
required: "This field is required",
minLength: "minimum length is {{1}}",
requiredTrue: "allowed requiredTrue only"
}
});
let user = new UserModel();
let job1 = new JobModel();
job1.jobName = 'Angular'
job1.jobValue = true;
let job2 = new JobModel();
job2.jobName = 'Vue'
job2.jobValue = false
user.jobs = new Array<JobModel>();
user.jobs.push(job1);
user.jobs.push(job2);
this.userForm = this.formBuilder.formGroup(user);
}
}
แสดง errorMessage ที่ html template
<!-- app.component.html -->
<form [formGroup]="myForm">
<div>
<h3>Jobs</h3>
<div formArrayName="jobs" *ngFor="let item of userForm?.get('jobs')?.controls; let i = index;">
<div [formGroupName]="i">
<input type="checkbox" formControlName="jobValue">
<label>
{{ item.get('jobName').value }}
</label>
</div>
<div style="color:red;">
{{ item.get('jobValue')?.errorMessage }}
</div>
</div>
jobs valid: {{ userForm.get('jobs').valid }}
</div>
</form>
แค่นี้เราก็จะได้ formGroupArray แบบง่ายๆมาใช้แล้วครับ
Top comments (0)