当前位置: 首页 > news >正文

@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);
  }
}

 

转载于:https://www.cnblogs.com/Nyan-Workflow-FC/p/8044694.html

相关文章:

  • 解决getOutputStream() has already been called for this response
  • spring boot下thymeleaf全局静态变量配置
  • ajax提交数据处理总结
  • django.http.response中HttpResponse 子类
  • SpringMVC三种异常处理方式
  • .NET 常见的偏门问题
  • CentOS6.4 安装LVS-RRD监控LVS
  • java8集合--LinkedList纯源码
  • 函数:递归是神马 - 零基础入门学习Python022
  • OSS控制台新增函数计算处理事件入口
  • 抽象类和接口
  • ABP理论学习之SignalR集成
  • Eclipse Java EE IDE 创建 Dynamic Web project问题
  • 集成第三方接口的技巧总结
  • 开始VS 2012 中LightSwitch系列的第2部分:感受关爱——定义数据关系
  • -------------------- 第二讲-------- 第一节------在此给出链表的基本操作
  • 【翻译】Mashape是如何管理15000个API和微服务的(三)
  • 2019年如何成为全栈工程师?
  • Android 架构优化~MVP 架构改造
  • Consul Config 使用Git做版本控制的实现
  • Debian下无root权限使用Python访问Oracle
  • download使用浅析
  • JavaScript工作原理(五):深入了解WebSockets,HTTP/2和SSE,以及如何选择
  • MD5加密原理解析及OC版原理实现
  • Mybatis初体验
  • spring + angular 实现导出excel
  • uva 10370 Above Average
  • Vue.js源码(2):初探List Rendering
  • 创建一个Struts2项目maven 方式
  • raise 与 raise ... from 的区别
  • ## 临床数据 两两比较 加显著性boxplot加显著性
  • #pragma data_seg 共享数据区(转)
  • (13)Hive调优——动态分区导致的小文件问题
  • (70min)字节暑假实习二面(已挂)
  • (C语言)输入一个序列,判断是否为奇偶交叉数
  • (html5)在移动端input输入搜索项后 输入法下面为什么不想百度那样出现前往? 而我的出现的是换行...
  • (TipsTricks)用客户端模板精简JavaScript代码
  • (超简单)使用vuepress搭建自己的博客并部署到github pages上
  • (学习日记)2024.04.04:UCOSIII第三十二节:计数信号量实验
  • (一)Mocha源码阅读: 项目结构及命令行启动
  • (一)硬件制作--从零开始自制linux掌上电脑(F1C200S) <嵌入式项目>
  • ***微信公众号支付+微信H5支付+微信扫码支付+小程序支付+APP微信支付解决方案总结...
  • .equals()到底是什么意思?
  • .NET CORE 2.0发布后没有 VIEWS视图页面文件
  • .NET 动态调用WebService + WSE + UsernameToken
  • .net 使用$.ajax实现从前台调用后台方法(包含静态方法和非静态方法调用)
  • .NET 中各种混淆(Obfuscation)的含义、原理、实际效果和不同级别的差异(使用 SmartAssembly)
  • .Net环境下的缓存技术介绍
  • .NET基础篇——反射的奥妙
  • .NET微信公众号开发-2.0创建自定义菜单
  • .NET中的十进制浮点类型,徐汇区网站设计
  • /ThinkPHP/Library/Think/Storage/Driver/File.class.php  LINE: 48
  • @Autowired和@Resource的区别
  • [ element-ui:table ] 设置table中某些行数据禁止被选中,通过selectable 定义方法解决
  • [ web基础篇 ] Burp Suite 爆破 Basic 认证密码