angular - 使用元数据在 angular2 中创建动态表单

标签 angular

我正在尝试使用元数据创建 CRUD 表单。我创建的是一个非常基本的自定义组件版本,它从模型创建一个表单。但是此时的自定义表单不会更新父模型。

如何处理从大控制(参见代码)到父级的更改流?我想我需要的是一些功能,比如 ng-model 指令。如果解决方案可扩展以允许验证,那就太好了。

动态表单基础版: http://plnkr.co/edit/BW6hluJ0PZG5GF5gsO6G?p=preview

import {Component, View, bootstrap, CORE_DIRECTIVES} from 'angular2/angular2';
import {FORM_DIRECTIVES, FORM_BINDINGS, NgFormModel, ControlGroup, Control, Validators} from 'angular2/forms';


@Component({selector: 'great-control', properties: ['column', 'value: data']})
@View({
  template: `
  <template [ng-if]="column.visible">
      <div class="pure-control-group">
        <span [ng-switch]="htmlElementType">
           <template [ng-switch-when]="'input'">
             <label [attr.for]="column.name">{{column.display}}</label>
             <input id="column.name" [attr.type]="computeInputSubType()" [(ng-model)]="value" 
                [attr.placeholder]="column.display"> {{value}}
           </template>
           <template [ng-switch-when]="'checkbox'">
             <div class="pure-controls">
              <label for="column.name" class="pure-checkbox">
                  <input id="column.name" type="checkbox" [(ng-model)]="value"> Toggle and see the change {{value}}
              </label>
            </div>
           </template>
           <template [ng-switch-when]="'option'">
              <label [attr.for]="column.name">{{column.display}}</label>
              <select [(ng-model)]="value">
                  <option *ng-for="#key of column.values" [value]="key">{{key}}</option>
              </select>{{value}}
            </div>
           </template>
           <template [ng-switch-default]">
                   <span>Oops! This control type is unknown. Contact the creator</span>
            </template>
        </span>


      </div>
  </template>
  <template [ng-if]="!column.visible">
      There is a hidden control here because the column is set to invisible 
      <input type="hidden" [(ng-model)]="value" />
  </template>



  `,
  directives: [FORM_DIRECTIVES,CORE_DIRECTIVES]
})
class GreatControl {
  column: Object;
  value: Object;
  htmlElementType:string;
  constructor() { 
  }

  onInit(){
    this.htmlElementType = this.computeHtmlElementType();
  }

  computeHtmlElementType(): string {
    if (this.column.type == "boolean") {
      return "checkbox";
    } else if (this.column.type == "enum") {
      return "option";
    } else if (this.column.type == "text" || this.column.type == "email" || this.column.type == "number"){
      return "input"
    }else{
      return "unknown"
    }
  }

  computeInputSubType(){
    if(this.column.type == "text"){
      return "text";
    } else if(this.column.type == "email"){
      return "email";
    } else if( this.column.type == "number"){
      return "number";
    } else {
      return "text";
    }
  }
}


@Component({
  selector: 'app',
  bindings: [FORM_BINDINGS]
})
@View({
  template: `
    <div class="pure-g"><div class="pure-u-1-1">
      <form [ng-form-model]='form' class="pure-form pure-form-aligned">
        <fieldset>
          <great-control *ng-for="#t of columns" [column]="t" [data]="data[t.name]" >
          </great-control>
            <div class="pure-controls">
                <button type="submit" class="pure-button pure-button-primary">Submit</button>
            </div>
        </fieldset>
      </form>
    </div><div class="pure-u-1-1"><p>
      As of now this does not change. We need it to change
    <br><pre>{{dataString()}}</pre></p></div></div>`,
  directives: [FORM_DIRECTIVES, CORE_DIRECTIVES, GreatControl]
})
class App {
  data: Object ;
  columns = [
      {name: "column1", display:"This is number only", visible:true, type: "number", length:"10"},
      {name: "column2", display:"This a text field", visible:true, type: "text", length:"10"},
      {name: "column3", display:"Column 3", visible:false, type: "text", length:"10"},
      {name: "column4", display:"Toggle and see", visible:true, type: "boolean"},
      {name: "column5", display:"Column 5", visible:true, type: "enum", values:[ "Blue", "Yellow", "White"]}
    ];
  constructor() {
      this.data= { column1 : "10" , column3: "Not a secret",column4: false, column5: "Yellow" };
    }
  onSubmit(f) {
    console.log(this.data);
  }
  dataString(){
    return JSON.stringify(this.data, null, 2);
  }
  valueOf(obj) {
      if (obj !== undefined && obj !== null) return obj;
      else return "";
  }
}


bootstrap(App);

预期行为(非动态): http://plnkr.co/edit/kQ0sMT4jItvj3e5uLHtD?p=preview

import {Component, View, bootstrap, NgIf, CORE_DIRECTIVES} from 'angular2/angular2';
import {FORM_DIRECTIVES, FORM_BINDINGS, NgFormModel, ControlGroup, Control, Validators} from 'angular2/forms';

@Component({
  selector: 'app',
  bindings: [FORM_BINDINGS]
})
@View({
  template: `
    <div class="pure-g"><div class="pure-u-1-1">
      <form [ng-form-model]='form' class="pure-form pure-form-aligned">
        <fieldset>
            <div class="pure-control-group">
                <label [attr.for]="columns[0].name">{{columns[0].display}}</label>
                <input id="columns[0].name" type="number" [(ng-model)]="data[columns[0].name]" [attr.placeholder]="columns[0].display">
            </div>
            <div class="pure-control-group">
                <label [attr.for]="columns[1].name">{{columns[1].display}}</label>
                <input id="columns[1].name" type="text" [(ng-model)]="data[columns[1].name]" [attr.placeholder]="columns[1].display">
            </div>
            <div class="pure-control-group">
                There is a hidden control here because the column is set to invisible
                <input type="hidden" [(ng-model)]="data[columns[2].name]" />
            </div>
            <div class="pure-controls">
              <label for="columns[3].name" class="pure-checkbox">
                  <input id="columns[3].name" type="checkbox" [(ng-model)]="data[columns[3].name]"> Toggle and see the change
              </label>
            </div>
            <div class="pure-control-group">
                <label [attr.for]="columns[4].name">{{columns[4].display}}</label>
                <select [(ng-model)]="data[columns[4].name]">
                    <option *ng-for="#state of columns[4].values" [value]="state">{{state}}</option>
                </select>
            </div>
            <div class="pure-controls">
                <button type="submit" class="pure-button pure-button-primary">Submit</button>
            </div>
        </fieldset>
      </form>
    </div><div class="pure-u-1-1"><p><pre>{{dataString()}}</pre></p></div></div>`,
  directives: [FORM_DIRECTIVES, CORE_DIRECTIVES]
})
class App {
  data: Object ;
  columns = [
      {name: "column1", display:"This is number only", visible:true, type: "number", length:"10"},
      {name: "column2", display:"This a text field", visible:true, type: "text", length:"10"},
      {name: "column3", display:"Column 3", visible:false, type: "text", length:"10"},
      {name: "column4", display:"Toggle and see", visible:true, type: "boolean"},
      {name: "column5", display:"Column 5", visible:true, type: "enum", values:[ "Blue", "Yellow", "White"]}
    ];
  constructor() {
      this.data= { column1 : "10" , column3: "Not a secret",column4: false, column5: "Yellow" };
    }
  onSubmit(f) {
    console.log(this.data);
  }
  dataString(){
    return JSON.stringify(this.data, null, 2);
  }
  valueOf(obj) {
      if (obj !== undefined && obj !== null) return obj;
      else return "";
  }
}


bootstrap(App);

非常感谢任何解决此问题的建议。 提前感谢您的帮助。

最佳答案

您需要将您的值包装在一个对象中。 原始类型(字符串、数字、 bool 值和 co)按值传递(复制值),而对象实例按引用传递(复制对对象的引用)。

这是一个更新的插件: http://plnkr.co/edit/N1W8XqIS8ykU1Vsm7hjf?p=preview

export class Value {
  value: any;
  constructor(value) {
    this.value = value;
  }
}


@Component({selector: 'great-control', properties: ['column', 'value: data']})
@View({
  template: `
  <template [ng-if]="column.visible && value != null">
      <div class="pure-control-group">
        <span [ng-switch]="htmlElementType">
           <template [ng-switch-when]="'input'">
             <label [attr.for]="column.name">{{column.display}}</label>
             <input id="column.name" [attr.type]="computeInputSubType()" [(ng-model)]="value.value" 
                [attr.placeholder]="column.display"> {{value.value}}
           </template>
           <template [ng-switch-when]="'checkbox'">
             <div class="pure-controls">
              <label for="column.name" class="pure-checkbox">
                  <input id="column.name" type="checkbox" [(ng-model)]="value.value"> Toggle and see the change {{value.value}}
              </label>
            </div>
           </template>
           <template [ng-switch-when]="'option'">
              <label [attr.for]="column.name">{{column.display}}</label>
              <select [(ng-model)]="value.value">
                  <option *ng-for="#key of column.values" [value]="key">{{key}}</option>
              </select>{{value.value}}
            </div>
           </template>
           <template [ng-switch-default]">
                   <span>Oops! This control type is unknown. Contact the creator</span>
            </template>
        </span>


      </div>
  </template>
  <template [ng-if]="!column.visible">
      There is a hidden control here because the column is set to invisible 
      <input type="hidden" [(ng-model)]="value.value" />
  </template>



  `,
  directives: [FORM_DIRECTIVES,CORE_DIRECTIVES]
})
class GreatControl {
  column: Object;
  value: Value;
  htmlElementType:string;
  constructor() { 
  }

  onInit(){
    this.htmlElementType = this.computeHtmlElementType();
  }

  computeHtmlElementType(): string {
    if (this.column.type == "boolean") {
      return "checkbox";
    } else if (this.column.type == "enum") {
      return "option";
    } else if (this.column.type == "text" || this.column.type == "email" || this.column.type == "number"){
      return "input"
    }else{
      return "unknown"
    }
  }

  computeInputSubType(){
    if(this.column.type == "text"){
      return "text";
    } else if(this.column.type == "email"){
      return "email";
    } else if( this.column.type == "number"){
      return "number";
    } else {
      return "text";
    }
  }
}

关于angular - 使用元数据在 angular2 中创建动态表单,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32778163/

相关文章:

angular - 从父类调用子组件方法 - Angular

swift - 如何使用 Swift 将 Angular routerLink 传递到 WKWebview

typescript - angular2 CLI 项目中缺少一些 RxJS 运算符?该怎么办?

angular - Angular 组件的代码开销是多少

angular - 如何升级 Angular CLI 项目?

javascript - 如何逐行读取angular2上的csv文件

angular - karma : Angular 4 No provider for Service

angular - 如何测试是否从 angular 组件调用服务

angular - 如何使mat-select始终在angular2中的表单字段下打开?

twitter-bootstrap - Angular 2 Bootstrap 4 和 ng-bootstrap