导入所需模块:

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. HTTP首部信息说明

    1.Accept:告诉WEB服务器自己接受什么介质类型,*/* 表示任何类型,type/* 表示该类型下的所有子类型,type/sub-type.2.Accept-Charset:浏览器申明自己接收的 ...

  2. C#编写图书列表winform

    Book.cs文件 using System; using System.Collections.Generic; using System.Linq; using System.Text; usin ...

  3. 插入排序 Insertion Sort

    插入排序算法的运作如下: 通过构建有序序列,对于未排序数据,在已排序序列中从后向前扫描,找到相应位置并插入. 插入排序算法的实现我放在这里. 时间/空间复杂度: 最差时间复杂度 O(n^2) 最优时间 ...

  4. Python操作——Redi

    redis是一个key-value存储系统. 和Memcached类似,它支持存储的value类型相对更多,包括string(字符串).list(列表).hash(哈希).set(集合).zset(有 ...

  5. Excel 查找某一列中包含指定字符的单元格

    网上查找相关内容,个人感觉是另一种形式的过滤喽.有的说用FIND,有的用高级筛选.我查找时如下: 1.新拉一列,标注公式“=ISNUMBER(FIND("宣",B2))”,然后拉至 ...

  6. MySQL数据库(8)_MySQL数据库总结

    sql语句规范 sql是Structured Query Language(结构化查询语言)的缩写.SQL是专为数据库而建立的操作命令集,是一种功能齐全的数据库语言. 在使用它时,只需要发出“做什么” ...

  7. (from) Javascript 生成指定范围数值随机数

    from:http://blog.csdn.net/ilibaba/article/details/3741786 查手册后才知道, 介绍的信息少得可怜呐, 没有介绍生成 m-n 范围的随机数..., ...

  8. Python学习进程(2)Python环境的搭建

        本节主要介绍在windows和Linux平台上如何搭建Python编程环境.     (1)查看Python版本: windows: C:\Users\JMSun>python 'pyt ...

  9. OpenGL帧缓存对象(FBO:Frame Buffer Object)

    http://blog.csdn.net/dreamcs/article/details/7691690 转http://blog.csdn.net/xiajun07061225/article/de ...

  10. library-type:fr-unstanded vs fisrt-stand vs second-stanrd

    建库时是否是链特异性建库. Tophat2: --library-type The default is unstranded (fr-unstranded). If either fr-firsts ...