@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 ...
随机推荐
- Java并发—线程池框架Executor总结(转载)
为什么引入Executor线程池框架 new Thread()的缺点 每次new Thread()耗费性能 调用new Thread()创建的线程缺乏管理,被称为野线程,而且可以无限制创建,之间相互竞 ...
- PL/SQL连接ORACLE失败,ORA-12154: TNS: could not resolve the connect identifier specified
项目需要使用ORACLE,安装了oracle之后,使用PL/SQL连接,先是提示NOT logger ,后续不知道改了什么提示解析服务器id失败,重新装了之后更狠的直接来了个空白提示 一.安装PLS ...
- notepad++运行python代码
notepad++运行代码 在菜单栏中点击运行或按F5,在弹出的对话框中输入下面命令 cmd /k E:\py3.6\python.exe "$(FULL_CURRENT_PATH)&quo ...
- rails 增删改查
class InvoicesController < ApplicationController def index @invoices = Invoice.all end def show @ ...
- HBase基本知识介绍及典型案例分析
本次分享的内容主要分为以下五点: HBase基本知识: HBase读写流程: RowKey设计要点: HBase生态介绍: HBase典型案例分析. 首先我们简单介绍一下 HBase 是什么. HBa ...
- vagrant搭建
1.在官网下载对应的vagrant版本 https://www.vagrantup.com/downloads.html (下载最新版本) https://releases.hashicorp.com ...
- 每日练习level-7
1.有序列表.无序列表.自定义列表如何使用?写个简单的例子.三者在语义上有什么区别?使用场景是什么? 能否嵌套? 有序列表是一列使用数字进行标记的项目,它使用<li>包含于<ol&g ...
- redis 数据导入导出,实例内db迁移
源实例db0迁移至目标实例db1 [root@172.20.0.1 ~]# cat redis_mv.sh #!/bin/bash redis-cli -h -a password -n keys & ...
- MongoDB快速入门(九)- 投影
MongoDB投影 mongodb投影意义是只选择需要的数据,而不是选择整个一个文档的数据.如果一个文档有5个字段,只需要显示3个,只从中选择3个字段. MongoDB的find()方法,解释了Mon ...
- 如何用Spring框架的<form:form>标签实现REST风格的增删改查操作
1.首先创建两个bean类,Employee(职工)和Department(部门),一个部门可以有多个职工 Employee类(属性:职工ID:id:姓名:lastName:邮箱:email:性别:g ...