@angular/cli项目构建--Dynamic.Form
导入所需模块:
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的更多相关文章
- @angular/cli项目构建--Dynamic.Form(2)
form-item-control.service.ts update @Injectable() export class FormItemControlService { constructor( ...
- @angular/cli项目构建--组件
环境:nodeJS,git,angular/cli npm install -g cnpm --registry=https://registry.npm.taobao.org cnpm instal ...
- @angular/cli项目构建--modal
环境准备: cnpm install ngx-bootstrap-modal --save-dev impoerts: [BootstrapModalModule.forRoot({container ...
- @angular/cli项目构建--路由2
app.module.ts update const routes: Routes = [ {path: '', redirectTo: '/home', pathMatch: 'full'}, {p ...
- @angular/cli项目构建--路由1
app.module.ts import {BrowserModule} from '@angular/platform-browser'; import {NgModule} from '@angu ...
- @angular/cli项目构建--animations
使用方法一(文件形式定义): animations.ts import { animate, AnimationEntryMetadata, state, style, transition, tri ...
- @angular/cli项目构建--interceptor
JWTInterceptor import {Injectable} from '@angular/core'; import {HttpEvent, HttpHandler, HttpInterce ...
- @angular/cli项目构建--路由3
路由定位: modifyUser(user) { this.router.navigate(['/auction/users', user.id]); } 路由定义: {path: 'users/:i ...
- @angular/cli项目构建--httpClient
app.module.ts update imports: [ HttpClientModule] product.component.ts import {Component, OnInit} fr ...
随机推荐
- What's the difference between 'Even if' and 'Even though'?
为一个英语词组语法写一篇Blog: even if 与 even though 这两个词组大致意思相当,但强调的侧重有所不同. even if与even though的区别: even if一般引导的 ...
- SpringMVC:学习笔记(5)——数据绑定及表单标签
SpringMVC——数据绑定及表单标签 理解数据绑定 为什么要使用数据绑定 基于HTTP特性,所有的用户输入的请求参数类型都是String,比如下面表单: 按照我们以往所学,如果要获取请求的所有参数 ...
- selection createTextRange setSelectionRange
http://www.cnblogs.com/rainman/archive/2011/02/27/1966482.html http://www.zhangxinxu.com/wordpress/2 ...
- UI控件之UITextField
UITextField:文本框:用来输入一行文本,父类是UIControl UITextField *field1=[[UITextField alloc]initWithFrame:CGRectMa ...
- flex 实现图片播放 方案二 把临时3张图片预加载放入内存
该方案,是预加载:前一张,当前,下一张图片,一共3张图片放入内存中.这样对内存的消耗可以非常小,加载之后的图片就释放内存. 下面示例一个是类ImagePlayers,一个是index.mxml pac ...
- 树莓派打造对话机器人 Python(转)
工具列表 1. **树莓派**(型号不要求,本人使用的是3B) 2. **usb麦克风**(某宝有卖,我就不打广告了) 用来录音 3. **音响或者喇叭**(某宝也有卖) 用来播放 以上就是需要的工具 ...
- INSPIRED启示录 读书笔记 - 第29章 大公司如何创新
大公司实现创新的方法 20%法则:谷歌的程序员有20%的工作时间可以用来从事创新研究,这个方法最早是从施乐帕克研究所学来的.20%法则鼓励普通员工自己尝试各种想法,让员工打心底愿意倾注更多的激情和汗水 ...
- Spring中为什么实体类不用注入
要理解为什么不用注入,首先就清楚注入的目的是什么?如果不注入,在程序中要使用某个类对象的方法,则需要去new一个对象.然后我们调用其中的方法,众所周知"程序=算法+数据".不失一般 ...
- 算法总结之 构造数组MaxTree
一个数组的MaxTree定义如下: 数组必须没有重复元素 MaxTree是一颗二叉树,数组的每一个值对应一个二叉树的节点 包括MaxTre树在内且在其中的每一颗子树上,值最大的节点都是树的头 给定一个 ...
- Tensorflow 从零开始
1.安装pip pip是一个用于管理和安装Python包的工具,类似于LINUX 的yum命令一样! 命令(Ubuntu系统):sudo apt-get install python-pip 验证安装 ...