一步步封裝完善一個資料驅動型-表單模型

楊明明發表於2018-04-08

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地址

相關文章