新聞中心
構(gòu)建動態(tài)表單
許多表單(比如問卷)可能在格式和意圖上都非常相似。為了更快更輕松地生成這種表單的不同版本,你可以根據(jù)描述業(yè)務(wù)對象模型的元數(shù)據(jù)來創(chuàng)建動態(tài)表單模板。然后就可以根據(jù)數(shù)據(jù)模型中的變化,使用該模板自動生成新的表單。

如果你有這樣一種表單,其內(nèi)容必須經(jīng)常更改以滿足快速變化的業(yè)務(wù)需求和監(jiān)管需求,該技術(shù)就特別有用。一個典型的例子就是問卷。你可能需要在不同的上下文中獲取用戶的意見。用戶要看到的表單格式和樣式應(yīng)該保持不變,而你要提的實際問題則會因上下文而異。
在本教程中,你會構(gòu)建一個渲染基本問卷的動態(tài)表單。你要為正在找工作的英雄們建立一個在線應(yīng)用。英雄管理局會不斷修補應(yīng)用流程,但是借助動態(tài)表單,你可以動態(tài)創(chuàng)建新的表單,而無需修改應(yīng)用代碼。
本教程將指導你完成以下步驟。
- 為項目啟用響應(yīng)式表單。
- 建立一個數(shù)據(jù)模型來表示表單控件。
- 使用范例數(shù)據(jù)填充模型。
- 開發(fā)一個組件來動態(tài)創(chuàng)建表單控件。
你創(chuàng)建的表單會使用輸入驗證和樣式來改善用戶體驗。它有一個 Submit 按鈕,這個按鈕只會在所有的用戶輸入都有效時啟用,并用色彩和一些錯誤信息來標記出無效輸入。
這個基本版可以不斷演進,以支持更多的問題類型、更優(yōu)雅的渲染體驗以及更高大上的用戶體驗。
參閱 現(xiàn)場演練 / 下載范例。
為項目啟用響應(yīng)式表單
動態(tài)表單是基于響應(yīng)式表單的。為了讓應(yīng)用訪問響應(yīng)式表達式指令,根模塊會從 ?@Angular/forms? 庫中導入 ?ReactiveFormsModule?。
以下代碼展示了此范例在根模塊中所做的設(shè)置。
- app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
import { NgModule } from '@angular/core';
import { AppComponent } from './app.component';
import { DynamicFormComponent } from './dynamic-form.component';
import { DynamicFormQuestionComponent } from './dynamic-form-question.component';
@NgModule({
imports: [ BrowserModule, ReactiveFormsModule ],
declarations: [ AppComponent, DynamicFormComponent, DynamicFormQuestionComponent ],
bootstrap: [ AppComponent ]
})
export class AppModule {
constructor() {
}
}
import { enableProdMode } from '@angular/core';
import { platformBrowserDynamic } from '@angular/platform-browser-dynamic';
import { AppModule } from './app/app.module';
import { environment } from './environments/environment';
if (environment.production) {
enableProdMode();
}
platformBrowserDynamic().bootstrapModule(AppModule);
創(chuàng)建一個表單對象模型
動態(tài)表單需要一個對象模型來描述此表單功能所需的全部場景。英雄應(yīng)用表單中的例子是一組問題 - 也就是說,表單中的每個控件都必須提問并接受一個答案。
此類表單的數(shù)據(jù)模型必須能表示一個問題。本例中包含 ?DynamicFormQuestionComponent?,它定義了一個問題作為模型中的基本對象。
這個 ?QuestionBase ?是一組控件的基類,可以在表單中表示問題及其答案。
export class QuestionBase {
value: T|undefined;
key: string;
label: string;
required: boolean;
order: number;
controlType: string;
type: string;
options: {key: string, value: string}[];
constructor(options: {
value?: T;
key?: string;
label?: string;
required?: boolean;
order?: number;
controlType?: string;
type?: string;
options?: {key: string, value: 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 || '';
this.type = options.type || '';
this.options = options.options || [];
}
}
定義控件類
此范例從這個基類派生出兩個新類,?TextboxQuestion ?和 ?DropdownQuestion?,分別代表不同的控件類型。當你在下一步中創(chuàng)建表單模板時,你會實例化這些具體的問題類,以便動態(tài)渲染相應(yīng)的控件。
|
控制類型 |
詳細信息 |
|---|---|
| 表示問題并讓用戶輸入。
? |
| 表示在選擇框中的一個選項列表。
|
編寫表單組
動態(tài)表單會使用一個服務(wù)來根據(jù)表單模型創(chuàng)建輸入控件的分組集合。下面的 ?QuestionControlService ?會收集一組 ?FormGroup ?實例,這些實例會消費問題模型中的元數(shù)據(jù)。你可以指定一些默認值和驗證規(guī)則。
import { Injectable } from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';
import { QuestionBase } from './question-base';
@Injectable()
export class QuestionControlService {
constructor() { }
toFormGroup(questions: QuestionBase[] ) {
const group: any = {};
questions.forEach(question => {
group[question.key] = question.required ? new FormControl(question.value || '', Validators.required)
: new FormControl(question.value || '');
});
return new FormGroup(group);
}
}
編寫動態(tài)表單內(nèi)容
動態(tài)表單本身就是一個容器組件,稍后你會添加它。每個問題都會在表單組件的模板中用一個 ?? 標簽表示,該標簽會匹配 ?DynamicFormQuestionComponent ?中的一個實例。
?DynamicFormQuestionComponent ?負責根據(jù)數(shù)據(jù)綁定的問題對象中的各種值來渲染單個問題的詳情。該表單依靠 ?[formGroup]? 指令來將模板 HTML 和底層的控件對象聯(lián)系起來。?DynamicFormQuestionComponent ?會創(chuàng)建表單組,并用問題模型中定義的控件來填充它們,并指定顯示和驗證規(guī)則。
- dynamic-form-question.component.html
{{question.label}} is required
import { Component, Input } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { QuestionBase } from './question-base';
@Component({
selector: 'app-question',
templateUrl: './dynamic-form-question.component.html'
})
export class DynamicFormQuestionComponent {
@Input() question!: QuestionBase;
@Input() form!: FormGroup;
get isValid() { return this.form.controls[this.question.key].valid; }
}
?DynamicFormQuestionComponent ?的目標是展示模型中定義的各類問題。你現(xiàn)在只有兩類問題,但可以想象將來還會有更多。模板中的 ?ngSwitch ?語句會決定要顯示哪種類型的問題。這里用到了帶有 ?formControlName ?和?formGroup ?選擇器的指令。這兩個指令都是在 ?ReactiveFormsModule ?中定義的。
提供數(shù)據(jù)
還要另外一項服務(wù)來提供一組具體的問題,以便構(gòu)建出一個單獨的表單。在本練習中,你將創(chuàng)建 ?QuestionService ?以從硬編碼的范例數(shù)據(jù)中提供這組問題。在真實世界的應(yīng)用中,該服務(wù)可能會從后端獲取數(shù)據(jù)。重點是,你可以完全通過 ?QuestionService ?返回的對象來控制英雄的求職申請問卷。要想在需求發(fā)生變化時維護問卷,你只需要在 ?questions ?數(shù)組中添加、更新和刪除對象。
?QuestionService ?以一個綁定到 ?@Input()? 的問題數(shù)組的形式提供了一組問題。
import { Injectable } from '@angular/core';
import { DropdownQuestion } from './question-dropdown';
import { QuestionBase } from './question-base';
import { TextboxQuestion } from './question-textbox';
import { of } from 'rxjs';
@Injectable()
export class QuestionService {
// TODO: get from a remote source of question metadata
getQuestions() {
const questions: QuestionBase[] = [
new DropdownQuestion({
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 TextboxQuestion({
key: 'firstName',
label: 'First name',
value: 'Bombasto',
required: true,
order: 1
}),
new TextboxQuestion({
key: 'emailAddress',
label: 'Email',
type: 'email',
order: 2
})
];
return of(questions.sort((a, b) => a.order - b.order));
}
}
創(chuàng)建一個動態(tài)表單模板
?DynamicFormComponent ?組件是表單的入口點和主容器,它在模板中用 ?? 表示。
?DynamicFormComponent ?組件通過把每個問題都綁定到一個匹配 ?DynamicFormQuestionComponent ?的 ?? 元素來渲染問題列表。
- dynamic-form.component.html
Saved the following values
{{payLoad}}
import { Component, Input, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';
import { QuestionBase } from './question-base';
import { QuestionControlService } from './question-control.service';
@Component({
selector: 'app-dynamic-form',
templateUrl: './dynamic-form.component.html',
providers: [ QuestionControlService ]
})
export class DynamicFormComponent implements OnInit {
@Input() questions: QuestionBase[] | null = [];
form!: FormGroup;
payLoad = '';
constructor(private qcs: QuestionControlService) {}
ngOnInit() {
this.form = this.qcs.toFormGroup(this.questions as QuestionBase[]);
}
onSubmit() {
this.payLoad = JSON.stringify(this.form.getRawValue());
}
}
顯示表單
要顯示動態(tài)表單的一個實例,?AppComponent ?外殼模板會把一個 ?QuestionService ?返回的 ?questions ?數(shù)組傳給表單容器組件 ??。
import { Component } from '@angular/core';
import { QuestionService } from './question.service';
import { QuestionBase } from './question-base';
import { Observable } from 'rxjs';
@Component({
selector: 'app-root',
template: `
Job Application for Heroes
`,
providers: [QuestionService]
})
export class AppComponent {
questions$: Observable[]>;
constructor(service: QuestionService) {
this.questions$ = service.getQuestions();
}
} 這個例子為英雄提供了一個工作申請表的模型,但是除了 ?QuestionService ?返回的對象外,沒有涉及任何跟英雄有關(guān)的問題。這種模型和數(shù)據(jù)的分離,允許你為任何類型的調(diào)查表復用這些組件,只要它與這個問題對象模型兼容即可。
確保數(shù)據(jù)有效
表單模板使用元數(shù)據(jù)的動態(tài)數(shù)據(jù)綁定來渲染表單,而不用做任何與具體問題有關(guān)的硬編碼。它動態(tài)添加了控件元數(shù)據(jù)和驗證標準。
要確保輸入有效,就要禁用 “Save” 按鈕,直到此表單處于有效狀態(tài)。當表單有效時,你可以單擊 “Save” 按鈕,該應(yīng)用就會把表單的當前值渲染為 JSON。
最終的表單如下圖所示。
當前題目:創(chuàng)新互聯(lián)Angular教程:Angular構(gòu)建動態(tài)表單
標題來源:http://m.fisionsoft.com.cn/article/dhodcge.html


咨詢
建站咨詢
