导入所需模块:

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. Eclipse中svn操作

    1.主干和分支间合并代码 合并根据目标不同分为2种: 1.分支合并到主干:主要用在修复完生产BUG,并上线之后.需把改动的代码合并到主干上. 2.主干合并到分支:公用的逻辑改动,需反映到所有并行的分支 ...

  2. Spring学习笔记5—为Spring添加REST功能

    1 关于REST 我的理解,REST就是将资源以最合适的形式在服务端和客户端之间传递. 系统中资源采用URL进行标识(可以理解为URL路径中带参数) 使用HTTP方法进行资源的管理(GET,PUT,P ...

  3. http的keep-alive和tcp的keepalive区别

    原文地址:http://blog.csdn.net/oceanperfect/article/details/51064574 1.HTTP Keep-Alive在http早期,每个http请求都要求 ...

  4. PhoneGap 兼容IOS上移20px(包括启动页,拍照)

    引自:http://stackoverflow.com/questions/19209781/ios-7-status-bar-with-phonegap 情景:在ios7下PhoneGap app会 ...

  5. C# Ajax 技术

    Ajax 是 Asynchronous JavaScript and XML(以及 DHTML 等)的缩写.下面是 Ajax 应用程序所用到的基本技术:• HTML 用于建立 Web 表单并确定应用程 ...

  6. java对象生命周期概述复习

    最近看了下java对象的生命周期做个笔记复习复习,很多不同的原因会使一个java类被初始化,可能造成类初始化的操作: 1)  创建一个java类的实例对象. 2)  调用一个java类中的静态方法. ...

  7. [转]springmvc中的常用的返回

    package com.boventech.learning.controller; import java.util.HashMap; import java.util.Map; import or ...

  8. 【HackerRank】Manasa and Stones

    Change language : Manasa 和 她的朋友出去徒步旅行.她发现一条小河里边顺序排列着带有数值的石头.她开始沿河而走,发现相邻两个石头上的数值增加 a 或者 b. 这条小河的尽头有一 ...

  9. Python编程-常用模块及方法

    常用模块介绍 一.time模块 在Python中,通常有这几种方式来表示时间: 时间戳(timestamp):通常来说,时间戳表示的是从1970年1月1日00:00:00开始按秒计算的偏移量.我们运行 ...

  10. Python mysql表数据和json格式的相互转换

    功能: 1.Python 脚本将mysql表数据转换成json格式 2.Python 脚本将json数据转成SQL插入数据库 表数据: SQL查询:SELECT id,NAME,LOCAL,mobil ...