@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 ...
随机推荐
- mysql数据库补充知识1 安装数据库破解数据库密码已经创建用户
一.安装MYSQL数据库 1.yum安装 #二进制rpm包安装 yum -y install mysql-server mysql 2.源码安装 1.解压tar包 cd /software tar ...
- ASP.NET,什么是MVC,MVC的简单介绍
什么是MVC模式 MVC(Model-View-Controller,模型—视图—控制器模式)用于表示一种软件架构模式.它把软件系统分为三个基本部分:模型(Model),视图(View)和控制器(Co ...
- Android:日常学习笔记(8)———探究UI开发(5)
Android:日常学习笔记(8)———探究UI开发(5) ListView控件的使用 ListView概述 A view that shows items in a vertically scrol ...
- linux 定时任务未执行php脚本
1,对于无法执行php文件,首先你应该考虑的问题是是否php代码有错误,你可以先检查一下你的php代码,或者可以在linux上面执行一下这个文件,看是否能够执行成功:如果成功了,就说明是crontab ...
- centos磁盘安装与磁盘分区方案
概述 关于centos分区的相关知识 无论怎么分区并不会影响系统文件目录的布局,如果只分/和swap这两个区 没有 usr , var , etc 等分区,在安装好后文件根目录里依然会有usr , v ...
- mybatis使用注意的细节
1.mybatis对sql执行后会对结果进行封装,如果没有返回任何记录,只是封装后的对象没有值,而对象并不为空null: (这个问题疏忽坑了两次,在对返回数组结果进行判断的时候,我用的if(Array ...
- UnsatisfiedLinkError X.so is 64-bit instead of 32-bit之Android 64 bit SO加载机制
http://blog.csdn.net/canney_chen/article/details/50633982 今天用户反馈应用闪退崩溃了.然后找呀找… 过程原来是这样的: 还是说下项目背景 应用 ...
- OC_NSFileManager
案例1:通过文件扩展名进行搜索文件 NSFileManager *manager = [NSFileManager defaultManager]; /* 在Mac OS X系统有一个代表主目录的速 ...
- HMM代码实现
按照网上的代码,自己敲了一下,改了一点点,理解加深了一下. 还有训练HMM的EM算法没看懂,下次接着看: 参考连接:http://www.cnblogs.com/hanahimi/p/4011765. ...
- Kafka详解一:Kafka简介
问题导读 1.Kafka有何特性?2.Kafka有哪些组件? 背景: 当今社会各种应用系统诸如商业.社交.搜索.浏览等像信息工厂一样不断的生产出各种信息,在大数据时代,我们面临如下几个挑战: ...