一步步封裝完善一個數據驅動型-表單模型

angular schema form 數據區動表單

項目演示地址css

項目github地址html

  • 需求分析

根據給定的schema數據來生成移動端的數據表單。剛想到這個需求,我也沒啥思路!先作一個簡單的,一步一步來,總會實現的!git

需求簡化

咱們實現一個動態生成組件的功能,簡化到這一步,我想到了上一篇文章10分鐘快速上手angular cdk,提到cdk裏面有一個portal能夠實現,既然有了思路那就動手吧!github

<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表單json

繼續深化-動態建立組件

第一個小目標咱們已經實現了,下面接着深度優化。這也是拿到一個需求的正常思路,先作着! 說真的,我也是一面寫文章一面整理思路,由於我發現有的時候,寫出來的東西思路會很清晰,就想之前喜歡蹲在廁所裏敲代碼腦子轉的很快同樣!bash

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);
    });
  }
}
複製代碼

服務實現ide

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用於生成組件。post

@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的表單。 下面咱們繼續深化,加上表單驗證ui

  • 表單驗證邏輯
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地址

相關文章
相關標籤/搜索