一步步封装完善一个数据驱动型-表单模型

angular schema form 数据区动表单

项目演示地址

项目github地址

  • 需求分析

根据给定的schema数据来生成移动端的数据表单。刚想到这个需求,我也没啥思路!先做一个简单的,一步一步来,总会实现的!

需求简化

我们实现一个动态生成组件的功能,简化到这一步,我想到了上一篇文章10分钟快速上手angular cdk,提到cdk里面有一个portal可以实现,既然有了思路那就动手吧!

<ng-container *ngFor="let item of list">
  <ng-container [cdkPortalOutlet]="item"></ng-container>
</ng-container>
import { Component, OnInit } from '@angular/core';
import { FieldInputComponent } from 'iwe7/form/src/field-input/field-input.component';
import { ComponentPortal } from '@angular/cdk/portal';
@Component({
  selector: 'form-container',
  templateUrl: './form-container.component.html',
  styleUrls: ['./form-container.component.scss']
})
export class FormContainerComponent implements OnInit {
  list: any[] = [];
  constructor() {}

  ngOnInit() {
    const inputPortal = new ComponentPortal(FieldInputComponent);
    this.list.push(inputPortal);
  }
}

这样我们就以最简单的方式生成了一个input表单

继续深化-动态创建组件

第一个小目标我们已经实现了,下面接着深度优化。这也是拿到一个需求的正常思路,先做着!
说真的,我也是一面写文章一面整理思路,因为我发现有的时候,写出来的东西思路会很清晰,就想以前喜欢蹲在厕所里敲代码脑子转的很快一样!

import { Component, OnInit } from '@angular/core';
import { FieldRegisterService } from 'iwe7/form/src/field-register.service';

@Component({
  selector: 'form-container',
  templateUrl: './form-container.component.html',
  styleUrls: ['./form-container.component.scss']
})
export class FormContainerComponent implements OnInit {
  list: any[] = [
    {
      type: 'input'
    }
  ];
  constructor(public register: FieldRegisterService) {}

  ngOnInit() {
    // 这里集成了一个服务,用来提供Portal
    this.list.map(res => {
      res.portal = this.register.getComponentPortal(res.type);
    });
  }
}

服务实现

import { Injectable, InjectionToken, Type, Injector } from '@angular/core';
import { ComponentPortal } from '@angular/cdk/portal';
import { FieldInputComponent } from './field-input/field-input.component';

export interface FormFieldData {
  type: string;
  component: Type<any>;
}

export const FORM_FIELD_LIBRARY = new InjectionToken<
  Map<string, FormFieldData>
>('FormFieldLibrary', {
  providedIn: 'root',
  factory: () => {
    const map = new Map();
    map.set('input', {
      type: 'input',
      component: FieldInputComponent
    });
    return map;
  }
});
@Injectable()
export class FieldRegisterService {
  constructor(public injector: Injector) {}
  // 通过key索引,得到一个portal
  getComponentPortal(key: string) {
    const libs = this.injector.get(FORM_FIELD_LIBRARY);
    const component = libs.get(key).component;
    return new ComponentPortal(component);
  }
}

继续深化-发现问题,重新整理思路

这样我们就通过一个给定的list = [{type: 'input'}] 来动态生成一个组件
接下来,我们继续完善这个input,给他加上name[表单提交时的key],placeholder[输入提醒],label[标题],value[默认之],并正确显示!
这个时候我们发现,portal没有提供传递input数据的地方!那只有换方案了,看来他只适合简单的动态生成模板。下面我们自己封装一个directive用于生成组件。

@Directive({
  selector: '[createComponent],[createComponentProps]'
})
export class CreateComponentDirective
  implements OnInit, AfterViewInit, OnChanges {
  @Input() createComponent: string;
  // 输入即传入进来的json
  @Input() createComponentProps: any;

  componentInstance: any;
  constructor(
    public register: FieldRegisterService,
    public view: ViewContainerRef
  ) {}

  ngOnInit() {}
  // 当输入变化时,重新生成组件
  ngOnChanges(changes: SimpleChanges) {
    if ('createComponent' in changes) {
      this.create();
    }
    if ('createComponentProps' in changes) {
      this.setProps();
    }
  }

  setProps() {
    if (!!this.componentInstance) {
      this.componentInstance.props = this.createComponentProps;
      this.componentInstance.updateValue();
    }
  }

  create() {
    // 清理试图
    this.view.clear();
    // 创建并插入component
    const component = this.register.getComponent(this.createComponent);
    const elInjector = this.view.parentInjector;
    const componentFactoryResolver = elInjector.get(ComponentFactoryResolver);
    const componentFactory = componentFactoryResolver.resolveComponentFactory(
      component
    );
    const componentRef = this.view.createComponent(componentFactory);
    // 保存一下,方便后面使用
    this.componentInstance = componentRef.instance;
    this.setProps();
  }
}
  • 改造之前的代码
<ng-container *ngFor="let item of list">
  <ng-container *createComponent="item.type;props item;"></ng-container>
</ng-container>
export class FormContainerComponent implements OnInit {
  list: any[] = [
    {
      type: 'input',
      name: 'realname',
      label: '姓名',
      placeholder: '请输入姓名',
      value: ''
    }
  ];
  constructor() {}
  ngOnInit() {}
}

改造后的注册器

import {
  Injectable,
  InjectionToken,
  Type,
  Injector,
  ViewContainerRef,
  NgModuleRef,
  ComponentFactoryResolver
} from '@angular/core';
import { ComponentPortal } from '@angular/cdk/portal';
import { FieldInputComponent } from './field-input/field-input.component';

export interface FormFieldData {
  type: string;
  component: Type<any>;
}

export const FORM_FIELD_LIBRARY = new InjectionToken<
  Map<string, FormFieldData>
>('FormFieldLibrary', {
  providedIn: 'root',
  factory: () => {
    const map = new Map();
    map.set('input', {
      type: 'input',
      component: FieldInputComponent
    });
    return map;
  }
});
@Injectable()
export class FieldRegisterService {
  constructor(
    public injector: Injector,
    private moduleRef: NgModuleRef<any>
  ) {}
  // 通过key索引,得到一个portal
  getComponent(key: string) {
    const libs = this.injector.get(FORM_FIELD_LIBRARY);
    const component = libs.get(key).component;
    return component;
  }
}
  • Input组件
export class FieldInputComponent implements OnInit, OnChanges {
  label: string = 'label';
  name: string = 'name';
  value: string = '';
  placeholder: string = 'placeholder';
  id: any;

  @Input() props: any;
  constructor(public injector: Injector) {
    this.id = new Date().getTime();
  }

  ngOnChanges(changes: SimpleChanges) {
    if ('props' in changes) {
      this.updateValue();
    }
  }

  // 更新配置项目
  updateValue() {
    const { label, name, value, placeholder } = this.props;
    this.label = label || this.label;
    this.name = name || this.name;
    this.value = value || this.value;
    this.placeholder = placeholder || this.placeholder;
  }

  ngOnInit() {}
}

继续深化-加入表单验证

到目前位置我们已经实现了基础功能,根据传入进来的schema成功创建了一个仅有input的表单。
下面我们继续深化,加上表单验证

  • 表单验证逻辑

export class FormValidators {
  static required(value): ValidatorFn {
    return (control: AbstractControl): ValidationErrors | null => {
      const result = Validators.required(control);
      if (!result) {
        return null;
      }
      return {
        ...value,
        ...result
      };
    };
  }
  static maxLength(value): ValidatorFn {
    return (control: AbstractControl): ValidationErrors | null => {
      const result = Validators.maxLength(value.limit)(control);
      if (!result) {
        return null;
      }
      return {
        ...value,
        ...result
      };
    };
  }
  static minLength(value): ValidatorFn {
    return (control: AbstractControl): ValidationErrors | null => {
      const result = Validators.minLength(value.limit)(control);
      if (!result) {
        return null;
      }
      return {
        ...value,
        ...result
      };
    };
  }
}
@Injectable()
export class ValidatorsHelper {
  getValidator(key: string): ValidatorFn {
    return FormValidators[key];
  }
}
  • html
<label [attr.for]="'input_'+id" [formGroup]="form">
  {{label}}
  <input [formControlName]="name" [attr.id]="'input_'+id" #input [attr.name]="name" [attr.value]="value" [attr.placeholder]="placeholder"
  />
  <div *ngIf="!form.get(name).valid">{{form.get(name).errors.msg}}</div>
</label>
export class FieldInputComponent implements OnInit, OnChanges {
  label: string = 'label';
  name: string = 'name';
  value: string = '';
  placeholder: string = 'placeholder';
  validators: any = {};
  id: any;

  @Input() props: any;

  form: FormGroup;
  control: AbstractControl;

  @ViewChild('input') input: ElementRef;
  constructor(
    public injector: Injector,
    public fb: FormBuilder,
    public validatorsHelper: ValidatorsHelper
  ) {
    this.id = new Date().getTime();
    // 创建动态表单
    this.form = this.fb.group({});
  }

  ngOnChanges(changes: SimpleChanges) {
    if ('props' in changes) {
      this.updateValue();
    }
  }

  // 更新配置项目
  updateValue() {
    const { label, name, value, placeholder, validators } = this.props;
    this.label = label || this.label;
    this.name = name || this.name;
    this.value = value || this.value;
    this.placeholder = placeholder || this.placeholder;
    this.validators = validators || this.validators;
  }

  ngOnInit() {
    this.control = new FormControl(this.value, {
      validators: [],
      updateOn: 'blur'
    });
    this.control.clearValidators();
    const validators = [];
    Object.keys(this.validators).map(key => {
      const value = this.validators[key];
      const validator = this.validatorsHelper.getValidator(key);
      if (key === 'required') {
        validators.push(validator(value));
      } else {
        validators.push(validator(value));
      }
    });
    this.control.setValidators(validators);
    this.form.addControl(this.name, this.control);
    // 监听变化
    this.form.valueChanges.subscribe(res => {
      console.log(res);
    });
  }
}
list: any[] = [
    {
      type: 'input',
      name: 'realname',
      label: '姓名',
      placeholder: '请输入姓名',
      value: '',
      validators: {
        required: {
          limit: true,
          msg: '请输入您的姓名'
        },
        minLength: {
          limit: 3,
          msg: '最小长度为3'
        },
        maxLength: {
          limit: 10,
          msg: '最大长度为10'
        }
      }
    },
    {
      type: 'input',
      name: 'nickname',
      label: '昵称',
      placeholder: '请输入昵称',
      value: '',
      validators: {
        required: {
          limit: true,
          msg: '请输入您的昵称'
        },
        minLength: {
          limit: 3,
          msg: '昵称最小长度为3'
        },
        maxLength: {
          limit: 10,
          msg: '昵称最大长度为10'
        }
      }
    }
  ];

小结

目前位置我们已经实现了全部的功能,下面进一步规范后面的开发流程,编写相应的约束。
为后期扩展做准备

import { Input } from '@angular/core';
// 组件设置规范
export abstract class FieldBase {
  // 传进来的json数据
  @Input() props: { [key: string]: string };
  // 更新属性的值
  abstract updateValue(): void;
}
// json数据格式规范
export interface SchemaInterface {
  type?: string;
  name?: string;
  label?: string;
  placeholder?: string;
  value?: string;
  validators: {
    [key: string]: {
      limit: string;
      msg: string;
    };
  };
}
// 表单规范
export interface SchemasInterface {
  // 提交的url
  url?: string;
  // 提交成功
  success: {
    // 提交成功提醒
    msg?: string;
    // 提交成功跳转
    url?: string;
  };
  // 提交失败
  fail: {
    // 提交失败提醒
    msg?: string;
    url?: string;
  };
  // 表单设置
  fields: SchemaInterface[];
}

希望有更多的人参与这个项目!一起开发,一起讨论,一起进步!!

项目演示地址

项目github地址

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 159,569评论 4 363
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 67,499评论 1 294
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 109,271评论 0 244
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 44,087评论 0 209
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 52,474评论 3 287
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 40,670评论 1 222
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 31,911评论 2 313
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 30,636评论 0 202
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 34,397评论 1 246
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 30,607评论 2 246
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 32,093评论 1 261
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 28,418评论 2 254
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 33,074评论 3 237
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 26,092评论 0 8
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 26,865评论 0 196
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 35,726评论 2 276
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 35,627评论 2 270

推荐阅读更多精彩内容

  • Spring Cloud为开发人员提供了快速构建分布式系统中一些常见模式的工具(例如配置管理,服务发现,断路器,智...
    卡卡罗2017阅读 134,100评论 18 139
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 11,617评论 4 59
  • 对于语言的编辑能力和深入思考,需要微习惯不断的去实践,但是没有实践就是等于零。 今日小确幸: 和班班说道歉,说自己...
    尹莎阅读 103评论 0 0
  • 1.你一定有过这样的体验——事情发展着发展着感觉有点不对,注意到一些异象,但问题不大没有深究,结果问题很大,事情搞...
    琢磨概念者阅读 143评论 0 0
  • 由于python中这些模块之间具有相互依赖的关系,故在安装这些模块时的顺序如下 1.安装numpy #pipins...
    舒map阅读 690评论 0 0