準(zhǔn)備工作
使用ng new async-form創(chuàng)建一個新工程,在app.module.ts中引入ReactiveFormsModule模塊并在根模塊中導(dǎo)入
import { ReactiveFormsModule } from '@angular/forms';@NgModule({ imports: [ ReactiveFormsModule ]})構(gòu)建表單元素的基類
export class QuestionBase<T> { value: T;//表單元素的值 key: string;//表單元素鍵的名稱 label: string;//輸入元素的標(biāo)題 required: boolean;//是否必輸 order: number;//排序 controlType: string;//表單的類型 選擇框/文本輸入框 constructor(options: { value?: T, key?: string, label?: string, required?: boolean, order?: number, controlType?: string } = {}) { this.value = options.value; this.key = options.key || ''; this.label = options.label || ''; this.required = !!options.required; this.order = options.order === undefined ? 1 : options.order; this.controlType = options.controlType || ''; }}繼承表單元素的基類
選擇框元素的數(shù)據(jù)類型繼承基類,設(shè)置了controlType 為'dropdown'并新增了屬性options數(shù)組
import { QuestionBase } from './question-base';export class QuestionDropdown extends QuestionBase<string>{ controlType = "dropdown"; options: { key: string, value: string }[] = []; constructor(options: {} = {}) { super(options); this.options = options["options"] || []; }}文本輸入框元素的數(shù)據(jù)類型繼承了基類,設(shè)置了controlType 為'textbox',新增了type屬性,定義input的類型
import { QuestionBase } from './question-base';export class QuestionTextbox extends QuestionBase<string> { controlType = "textbox"; type:string; constructor(options:{} ={}){ super(options); this.type = options["type"]||"" }}生成數(shù)據(jù)
根據(jù)表單元素的派生類生成表單的數(shù)據(jù)。可以引入一個服務(wù)類,提供表單數(shù)據(jù)。
getQuestions(){ let questions:QuestionBase<any>[]=[ new QuestionDropdown({ key:'brave', label:'Bravery Rating', options:[ {key:'solid',value:'Solid'}, {key:'great',value:'Great'}, {key:'good',value:'Good'}, {key:'unproven',value:'Unproven'} ], order:3 }), new QuestionTextbox({ key:'firstName', label:'First name', value:"Bombasto", required:true, order:1 }), new QuestionTextbox({ key:'emailAddress', label:"Email", type:'email', order:2 }) ]; return questions.sort((a, b) => a.order - b.order); }將數(shù)據(jù)轉(zhuǎn)成FormControl類型
可以專門提供一個服務(wù)類,將表單的數(shù)據(jù)轉(zhuǎn)成FormControl類型
toFormGroup(questions: QuestionBase<any>[]) { let group: any = {}; questions.forEach(question => { group[question.key] = question.required?new FormControl(question.value||"",Validators.required) :new FormControl(question.value||""); }); return new FormGroup(group); }
新聞熱點(diǎn)
疑難解答
圖片精選