@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);
  }
}
时间: 2024-08-06 22:41:08

@angular/cli项目构建--Dynamic.Form的相关文章

@angular/cli项目构建--组件

环境:nodeJS,git,angular/cli npm install -g cnpm cnpm install -g @angular/cli ng new angularDemo ng -v ng set --global packageManager=cnpm npm install jquery --save npm install bootstrap --save npm install @type/jquery --save-dev npm install @type/boots

@angular/cli项目构建--路由1

app.module.ts import {BrowserModule} from '@angular/platform-browser'; import {NgModule} from '@angular/core'; import {AppComponent} from './app.component'; import {NavBarComponent} from './nav-bar/nav-bar.component'; import {FooterComponent} from '.

@angular/cli项目构建--路由2

app.module.ts update const routes: Routes = [ {path: '', redirectTo: '/home', pathMatch: 'full'}, {path: 'home', component: HomeComponent}, {path: 'login', component: LoginComponent}, {path: '**', component: Code404Component} ]; nav-bar.compoonent.ht

@angular/cli项目构建--httpClient

app.module.ts update imports: [ HttpClientModule] product.component.ts import {Component, OnInit} from '@angular/core'; import {HttpClient} from '@angular/common/http'; import {Observable} from 'rxjs/Observable'; import * as _ from 'lodash'; @Compone

@angular/cli项目构建--modal

环境准备: cnpm install ngx-bootstrap-modal --save-dev impoerts: [BootstrapModalModule.forRoot({container: ducument.body})] usage: import { Component } from '@angular/core'; import { DialogService } from "ngx-bootstrap-modal"; @Component({ selector:

Angular Cli 设置 淘宝的NPM 镜像

Angular CLI 是 构建angular2 项目的 脚手架工具. 安装Angular-Cli  需要先安装 Node.js. 大家可以去 node.js 官网下载. 说明:因为npm安装插件是从国外服务器下载,受网络影响大,可能出现异常.所以我们需要适用淘宝的镜像. http://registry.npm.taobao.org/ 设置方法如下:npm install -g cnpm  --registry=https://registry.npm.taobao.org 然后使用 cnpm 

Angular CLI的简单使用(2)

刚才创建了myApp这个项目,看一下这个项目的文件结构.    项目文件概览 Angular CLI项目是做快速试验和开发企业解决方案的基础. 你首先要看的文件是README.md. 它提供了一些如何使用CLI命令的基础信息. 如果你想了解 Angular CLI 的工作原理,请访问 Angular CLI 的仓库及其Wiki. 有些生成的文件你可能觉得陌生.接下来就讲讲它们. src文件夹 你的应用代码位于src文件夹中. 所有的Angular组件.模板.样式.图片以及你的应用所需的任何东西都

Angular环境准备和Angular cli

Angular4.0来了,更小,更快,改动少 接下来为Angular4.0准备环境和学会使用Angular cli项目 1.环境准备: 1)在开始工作之前我们必须设置好开发环境 如果你的机器上还没有安装Node.js和npm,请安装他们 (这里特别推荐使用淘宝的镜像cnpm,记得以后把npm的指令改为cnpm就可以了) npm install -g cnpm --registry=https://registry.npm.taobao.org 然后我们可以通过node -v和cnpm -v来分别

内网安装angular/cli

博主在外网搭建angular/cli项目迁移到内网时无法启动npm start,于是找了好多方法探索,因而发现时angular/cli需要全局安装,外网只需要npm i -g @angular/cli就好了,因为有npm帮你去下载:然而我这是在内网开发,于是想破了头找了网上的方法:window上亲测有效 Install Angular CLI Offline Install it in online machine and copy %appdata%/npm/node_modules/@ang