@angular/cli项目构建--Dynamic.Form(2)

form-item-control.service.ts update

@Injectable()
export class FormItemControlService {
  constructor(private formBuilder: FormBuilder) {
  }

  toFormGroup(formItems: FormItemBase<any>[]) {
    const group: any = {};
    formItems.forEach(formItem => {
      group[formItem.key] = formItem.required
        ? [formItem.value || '', Validators.required]
        : [formItem.value || ''];
    });
    return this.formBuilder.group(group);
  }
}

dynamic-form.component update

<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" maxlength="{{formItem.maxLength}}">

    <select [id]="formItem.key" *ngSwitchCase="'dropDown'" [formControlName]="formItem.key">
      <option *ngFor="let opt of formItem.options" [value]="opt.key">{{opt.value}}</option>
    </select>

    <div *ngFor="let opt of formItem.radioOptions">
      <input *ngSwitchCase="'radio'" [formControlName]="formItem.key"
             [id]="opt.key" type="radio" [value]="opt.key">
      <label [attr.for]="opt.key">{{opt.value}}</label>
    </div>

    <div *ngFor="let opt of formItem.checkOptions">
      <input *ngSwitchCase="'checkbox'" [formControlName]="formItem.key"
             [id]="opt.key" type="checkbox" [value]="opt.key">
      <label [attr.for]="opt.key">{{opt.value}}</label>
    </div>

  </div>

  <!--<div class="errorMessage" *ngIf="!isValid && form.get(formItem.key).touched">{{formItem.label}} is required</div>-->
  <div class="errorMessage"
       *ngIf="form.get(formItem.key).hasError('required') && form.get(formItem.key).touched">
    {{formItem.label}} is required
  </div>
</div>

 

posted @ 2017-12-28 09:32  Nyan  阅读(163)  评论(0编辑  收藏  举报