导入所需模块:

ReactiveFormsModule

DynamicFormComponent.html

<div [formGroup]="form">
<label [attr.for]="formItem.key">{{formItem.label}}</label>
<div [ngSwitch]="formItem.controlType"> <input *ngSwitchCase="'textbox'" [formControlName]="formItem.key"
[id]="formItem.key" [type]="formItem.type"> <select [id]="formItem.key" *ngSwitchCase="'dropdown'" [formControlName]="formItem.key">
<option *ngFor="let opt of formItem.options" [value]="opt.key">{{opt.value}}</option>
</select> </div> <div class="errorMessage" *ngIf="!isValid">{{formItem.label}} is required</div>
</div>

DynamicFormComponent.ts

import {Component, Input, OnInit} from '@angular/core';
import {FormItemBase} from './form-item-base';
import {FormGroup} from '@angular/forms'; @Component({
selector: 'app-dynamic-form',
templateUrl: './dynamic-form.component.html',
styleUrls: ['./dynamic-form.component.css']
})
export class DynamicFormComponent implements OnInit { @Input() formItem: FormItemBase<any>;
@Input() form: FormGroup; constructor() { } ngOnInit() {
}
get isValid() { return this.form.controls[this.formItem.key].valid; } }

FormItemBase.ts

export class FormItemBase<T> {
value: T;
key: string;
label: string;
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 || '';
}
}

FormTextbox.ts

import {FormItemBase} from './form-item-base';

export class FormTextbox extends FormItemBase<string> {
controlType = 'textbox';
type: string; constructor(options: {} = {}) {
super(options);
this.type = options['type'] || '';
}
}

FormDropdown.ts

import {FormItemBase} from './form-item-base';

export class FormDropdown extends FormItemBase<string> {
controlType = 'dropdown';
options: {key: string, value: string}[] = []; constructor(options: {} = {}) {
super(options);
this.options = options['options'] || [];
}
}

FormItemControl.ts

import {Injectable} from '@angular/core';
import {FormItemBase} from './form-item-base';
import {FormControl, FormGroup, Validators} from '@angular/forms'; @Injectable()
export class FormItemControlService {
constructor() {
} toFormGroup(formItems: FormItemBase<any>[]) {
const group: any = {};
formItems.forEach(formItem => {
group[formItem.key] = formItem.required
? new FormControl(formItem.value || '', Validators.required)
: new FormControl(formItem.value || '');
});
return new FormGroup(group);
}
}

QuestionComponent.html

<div class="container">
<app-question-form [questions]="questions"></app-question-form>
</div>

QuestionComponent.ts

import { Component, OnInit } from '@angular/core';
import {QuestionFromService} from './question-form/question-form.service'; @Component({
selector: 'app-question',
templateUrl: './question.component.html',
styleUrls: ['./question.component.css']
})
export class QuestionComponent implements OnInit { questions: any[]; constructor(questionFormService: QuestionFromService) {
this.questions = questionFormService.getQuestionFormItems();
} ngOnInit() {
} }

QuestionFormComponent.html

<div>
<form (ngSubmit)="onSubmit()" [formGroup]="form"> <div *ngFor="let question of questions" class="form-row">
<app-dynamic-form [formItem]="question" [form]="form"></app-dynamic-form>
</div> <div class="form-row">
<button type="submit" [disabled]="!form.valid">Save</button>
</div>
</form> <div *ngIf="payLoad" class="form-row">
<strong>Saved the following values</strong><br>{{payLoad}}
</div>
</div>

QuestionFormComponent.ts

import {Component, Input, OnInit} from '@angular/core';
import {FormGroup} from '@angular/forms';
import {FormItemBase} from '../../common/component/dynamic-form/form-item-base';
import {FormItemControlService} from '../../common/component/dynamic-form/form-item-control.service'; @Component({
selector: 'app-question-form',
templateUrl: './question-form.component.html',
styleUrls: ['./question-form.component.css']
})
export class QuestionFormComponent implements OnInit { form: FormGroup;
payLoad = '';
@Input()
questions: FormItemBase<any>[] = []; constructor(private fromItemControlService: FormItemControlService) {
} ngOnInit() {
this.form = this.fromItemControlService.toFormGroup(this.questions);
} onSubmit() {
this.payLoad = JSON.stringify(this.form.value);
} }

QuestionForm.service.ts

import {Injectable} from '@angular/core';
import {FormItemBase} from '../../common/component/dynamic-form/form-item-base';
import {FormDropdown} from '../../common/component/dynamic-form/form-dropdown';
import {FormTextbox} from '../../common/component/dynamic-form/form-textbox'; @Injectable()
export class QuestionFromService { getQuestionFormItems() {
const questionFormItems: FormItemBase<any>[] = [
new FormDropdown({
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 FormTextbox({
key: 'firstName',
label: 'First name',
value: 'Bombasto',
required: true,
order: 1
}), new FormTextbox({
key: 'emailAddress',
label: 'Email',
type: 'email',
required: false,
order: 2
})
];
return questionFormItems.sort((a, b) => a.order - b.order);
}
}

@angular/cli项目构建--Dynamic.Form的更多相关文章

  1. @angular/cli项目构建--Dynamic.Form(2)

    form-item-control.service.ts update @Injectable() export class FormItemControlService { constructor( ...

  2. @angular/cli项目构建--组件

    环境:nodeJS,git,angular/cli npm install -g cnpm --registry=https://registry.npm.taobao.org cnpm instal ...

  3. @angular/cli项目构建--modal

    环境准备: cnpm install ngx-bootstrap-modal --save-dev impoerts: [BootstrapModalModule.forRoot({container ...

  4. @angular/cli项目构建--路由2

    app.module.ts update const routes: Routes = [ {path: '', redirectTo: '/home', pathMatch: 'full'}, {p ...

  5. @angular/cli项目构建--路由1

    app.module.ts import {BrowserModule} from '@angular/platform-browser'; import {NgModule} from '@angu ...

  6. @angular/cli项目构建--animations

    使用方法一(文件形式定义): animations.ts import { animate, AnimationEntryMetadata, state, style, transition, tri ...

  7. @angular/cli项目构建--interceptor

    JWTInterceptor import {Injectable} from '@angular/core'; import {HttpEvent, HttpHandler, HttpInterce ...

  8. @angular/cli项目构建--路由3

    路由定位: modifyUser(user) { this.router.navigate(['/auction/users', user.id]); } 路由定义: {path: 'users/:i ...

  9. @angular/cli项目构建--httpClient

    app.module.ts update imports: [ HttpClientModule] product.component.ts import {Component, OnInit} fr ...

随机推荐

  1. Facebook支持python的开源预测工具Prophet

    Facebook 宣布开源一款基于 Python 和 R 语言的数据预测工具――“Prophet”,即“先知”.取名倒是非常直白. Facebook 表示,Prophet 相比现有预测工具更加人性化, ...

  2. 20171104 DOI Excel 导出

    1. OAOR 创建模板, Class name:SOFFICEINTEGRATIONClass type:  OTObject key:  ZZCSDRP_0030 2.双击表模板创建Excel 模 ...

  3. 深入理解MVC架构

    MVC MVC是一种设计模式(Design pattern),也就是一种解决问题的方法和思路, 是上世纪80年代提出的,到现在已经颇有历史了. MVC的意义在于指导开发者将数据与表现解耦,提高代码,特 ...

  4. 高阶函数,map,filter,sorted

    Map:对列表中的每个元素进行操作 >>> def f(x): ...    return x * x ... >>> map(f, [1, 2, 3, 4, 5, ...

  5. 常见Web源码泄露总结

    来自:http://www.hacksec.cn/Penetration-test/474.html 摘要 背景 本文主要是记录一下常见的源码泄漏问题,这些经常在web渗透测试以及CTF中出现. .h ...

  6. php异常处理类

    <?php header('content-type:text/html;charset=UTF-8'); // 创建email异常处理类 class emailException extend ...

  7. hadoop01

    RPC:异步系统的调用,webservice是RPC的一种.webservice用于不在同一个公司的系统调用,同一个公司用socket调用.就是RPC. Dubbo淘宝的RPC框架. Hadoop r ...

  8. ES6 随记(2)-- 解构赋值

    上一章请见: 1. ES6 随记(1)-- let 与 const 3. 解构赋值 a. 数组的解构赋值 let [a1, b1, c1] = [1, 2, 3]; console.log(a1, b ...

  9. freeswitch中集成使用ekho实现TTS功能一

    Linux下安装freeswitch并集成ekho实现TTS 1. linux下安装freeswitch就不多介绍了,具体链接网址: http://www.8000hz.com/archives/14 ...

  10. point-to-point(点对点) 网口

    点对点连接是两个系统或进程之间的专用通信链路.想象一下直接连接两个系统的一条线路.两个系统独占此线路进行通信.点对点通信的对立面是广播,在广播通信中,一个系统可以向多个系统传输. 点对点通信在OSI协 ...