网站首页 » 前端开发 » Angular 2+ » Angular 2+ 动态表单
上一篇:
下一篇:

Angular 2+ 动态表单

前言

这篇文章没什么技术含量,只是把官方的 DEMO 拷贝过来,样式修改了下而已,没有别的。这篇文章的重点是对官方 DEMO 代码注解,把那些我认为很可能让你困惑的地方作一些备注。

Angular 2+ 动态表单

动态表单

我们直接上码:

app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { ReactiveFormsModule } from '@angular/forms';
import { NgModule } from '@angular/core';

import { AppComponent } from './app.component';
import { DynamicFormComponent } from './dynamic-form.component';
import { DynamicFormQuestionComponent } from './dynamic-form-question.component';

@NgModule({
  imports: [BrowserModule, ReactiveFormsModule],
  declarations: [AppComponent, DynamicFormComponent, DynamicFormQuestionComponent],
  bootstrap: [AppComponent]
})
export class AppModule {
  constructor() {
  }
}
question-base.ts
export class QuestionBase<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 || '';
  }
}

QuestionBase<T> 中的 T 是一个类型变量,可以通过它定义一个泛型类。options 对象中的问号表示可选属性。说明 options 对象中属性是可选的。

question-textbox.ts
import { QuestionBase } from './question-base';

export class TextboxQuestion extends QuestionBase<string> {
  controlType = 'textbox';
  type: string;

  constructor(options: {} = {}) {
    super(options);
    this.type = options['type'] || '';
  }
}
question-dropdown.ts
import { QuestionBase } from './question-base';

export class DropdownQuestion extends QuestionBase<string> {
  controlType = 'dropdown';
  options: {key: string, value: string}[] = [];

  constructor(options: {} = {}) {
    super(options);
    this.options = options['options'] || [];
  }
}

extends 就是继承父类 QuestionBase<string>, QuestionBase 中的 string 就是给前面基类中的类型变量 T 赋值。可以像前面那样定义一个泛型类,我们就可以很方便的通过这个类型变量 T 来修改指定变量的类型(比如:上面的 value)。super(options); 访问父类中的构造函数,并传入 options 参数。更多关于 super 的用法可以看这里《ES6 中的 super 关键字》。

question-control.service.ts
import { Injectable }   from '@angular/core';
import { FormControl, FormGroup, Validators } from '@angular/forms';

import { QuestionBase } from './question-base';

@Injectable()
export class QuestionControlService {
  constructor() { }

  toFormGroup(questions: QuestionBase<any>[] ) {
    let group: any = {};

    questions.forEach(question => {
      group[question.key] = question.required ? new FormControl(question.value || '', Validators.required)
                                              : new FormControl(question.value || '');
    });
    return new FormGroup(group);
  }
}

questions: QuestionBase<any>[] 中的 QuestionBase<any>[] 表示一个元素为 QuestionBase<any> 类型的数组。

dynamic-form.component.html
<form (ngSubmit)="onSubmit()" [formGroup]="form" class="form-horizontal">
  <div class="panel panel-default">
    <div class="panel-heading">
      <h3 class="panel-title">Job Application for Heroes</h3>
    </div>
    <div class="panel-body">
      <div *ngFor="let question of questions" class="form-row">
        <app-question [question]="question" [form]="form"></app-question>
      </div>
      <div *ngIf="payLoad" class="form-row">
        <strong>Saved the following values</strong>
        <br>{{payLoad}}
      </div>
    </div>
    <div class="panel-footer text-right">
      <button type="submit" class="btn btn-primary" [disabled]="!form.valid">Save</button>
    </div>
  </div>
</form>
dynamic-form.component.ts
import { Component, Input, OnInit } from '@angular/core';
import { FormGroup } from '@angular/forms';

import { QuestionBase } from './question-base';
import { QuestionControlService } from './question-control.service';

@Component({
  selector: 'app-dynamic-form',
  templateUrl: './dynamic-form.component.html',
  providers: [QuestionControlService]
})
export class DynamicFormComponent implements OnInit {

  @Input() questions: QuestionBase<any>[] = [];
  form: FormGroup;
  payLoad = '';

  constructor(private qcs: QuestionControlService) { }

  ngOnInit() {
    this.form = this.qcs.toFormGroup(this.questions);
  }

  onSubmit() {
    this.payLoad = JSON.stringify(this.form.value);
  }
}
dynamic-form-question.component.html
<div [formGroup]="form">
  <div class="form-group">
    <label class="col-sm-2 control-label" [attr.for]="question.key" for="formGroupInputSmall">{{question.label}}</label>
    <div class="col-sm-10" [ngSwitch]="question.controlType">
      <input class="form-control" *ngSwitchCase="'textbox'" [formControlName]="question.key" [id]="question.key" [type]="question.type">
      <select class="form-control" [id]="question.key" *ngSwitchCase="'dropdown'" [formControlName]="question.key">
        <option *ngFor="let opt of question.options" [value]="opt.key">{{opt.value}}</option>
      </select>
    </div>
  </div>
  <div class="errorMessage" *ngIf="!isValid">{{question.label}} is required</div>
</div>
dynamic-form-question.component.ts
import { Component, Input } from '@angular/core';
import { FormGroup }        from '@angular/forms';

import { QuestionBase }     from './question-base';

@Component({
  selector: 'app-question',
  templateUrl: './dynamic-form-question.component.html'
})
export class DynamicFormQuestionComponent {
  @Input() question: QuestionBase<any>;
  @Input() form: FormGroup;
  get isValid() { return this.form.controls[this.question.key].valid; }
}
question.service.ts
import { Injectable }       from '@angular/core';

import { DropdownQuestion } from './question-dropdown';
import { QuestionBase }     from './question-base';
import { TextboxQuestion }  from './question-textbox';

@Injectable()
export class QuestionService {

  // Todo: get from a remote source of question metadata
  // Todo: make asynchronous
  getQuestions() {

    let questions: QuestionBase<any>[] = [

      new DropdownQuestion({
        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 TextboxQuestion({
        key: 'firstName',
        label: 'First name',
        value: 'Bombasto',
        required: true,
        order: 1
      }),

      new TextboxQuestion({
        key: 'emailAddress',
        label: 'Email',
        type: 'email',
        order: 2
      })
    ];

    return questions.sort((a, b) => a.order - b.order);
  }
}
app.component.ts
import { Component } from '@angular/core';

import { QuestionService } from './question.service';

@Component({
  selector: 'app-root',
  template: `
    <div  class="container">
      <app-dynamic-form [questions]="questions"></app-dynamic-form>
    </div>
  `,
  providers: [QuestionService]
})
export class AppComponent {
  questions: any[];

  constructor(service: QuestionService) {
    this.questions = service.getQuestions();
  }
}

providers: [QuestionService] 声明一个服务提供商,让组件访问同一个类实例。

  • 微信扫一扫,赏我

  • 支付宝扫一扫,赏我

声明

原创文章,不经本站同意,不得以任何形式转载,如有不便,请多多包涵!

本文永久链接:http://yunkus.com/angular-core-knowledge-dynamic-form/

Leave a Reply

Your email address will not be published. Required fields are marked *

评论 END