Angular2 创建模型嵌套表单 [英] Angular2 create model nested forms

查看:19
本文介绍了Angular2 创建模型嵌套表单的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试创建嵌套表单,但我被困在第二级并且不确定 addAttribute 和 removeAttribute 会是什么样子?

导出类 ExportFormComponent 实现 OnInit {公共出口表格:FormGroup;构造函数(私有formBuilder:FormBuilder){}ngOnInit() {this.exportForm = this.formBuilder.group( {数据类型: [''],项目: this.formBuilder.array( [this.initItem(),])});}初始化项目(){返回 this.formBuilder.group( {出口表达式:[''],描述: [''],可更新:[真],属性: this.formBuilder.array( [this.initAttribute(),])});}初始化属性(){返回 this.formBuilder.group( {出口表达式:[''],localizedRawField: [''],可本地化:[真],});}新增项目() {const control = this.exportForm.controls['items'];control.push( this.initItem() );}删除项目(我:数字){const control = this.exportForm.controls['items'];control.removeAt( i );}添加属性(){}移除属性( ) {}保存(导出配置:导出配置){控制台.log(exportConfiguration);}}

我的界面树

export interface ExportConfiguration {数据类型?:字符串,项目?:项目[],}导出接口项目{exportExpression?: 字符串,描述?:字符串,可更新?:布尔值,属性?:属性[],}导出接口属性{exportExpression?: 字符串,可本地化?:布尔值,localizedRawField?: 字符串,规则?:转换规则[]}导出接口 TransformationRule {数据路径键?:字符串,表达式检查?:布尔值,表达式?:字符串,}

编辑

好的,所以我使用发布的演示作为答案之一,但在以下 ( this.itemsCtrl.get( '${index}.attributes' ) as FormArray )

addAttribute( index: number ) {( this.itemsCtrl.get( '${index}.attributes' ) as FormArray ).push( this.initAttribute() );}

解决方案

首先我更喜欢在组件中创建引用来处理控件,而不是调用 .controls.get 一直都在.

因此,您的addremove功能 将像您的模板 一样干净.

可能是这样的:

exportForm: FormGroup;数据类型控件:表单控件;itemsCtrl: FormArray;构造函数(私有表单构建器:FormBuilder){}ngOnInit() {this.dataTypeCtrl = this.formBuilder.control('');this.itemsCtrl = this.formBuilder.array([this.initItem()]);this.exportForm = this.formBuilder.group( {数据类型:this.dataTypeCtrl,项目:this.itemsCtrl});}//...新增项目() {this.itemsCtrl.push(this.initItem());}删除项目(我:数字){this.itemsCtrl.removeAt(i);}添加属性(索引:数字){this.itemsCtrl.get(`${index}.attributes`).push(this.initAttribute())}removeAttribute(itemIndex: number, attrIndex: number) {this.itemsCtrl.get(`${itemIndex}.attributes`).removeAt(attrIndex)}

然后,在模板中您可以直接访问controls,如下所示:

<预><代码>...<div formArrayName="items" *ngFor="let itemCtrl of itemsCtrl.controls; let i = index"><div [formGroupName]="i"><button (click)="removeItem(i)">删除项目</button><input type="text" formControlName="description"><!-- 来自项目的其他输入--><button (click)="addAttribute(i)">添加属性</button><div formArrayName="attributes" *ngFor="let attributeCtrl of itemCtrl.get('attributes').controls; let j = index"><div [formGroupName]="j"><button (click)="removeAttribute(i, j)">移除属性</button><input type="text" formControlName="exportExpression"<!-- 来自属性的其他输入-->

参见演示

i am trying to create nested forms but i am stuck in the second level and not sure how the addAttribute and removeAttribute will look like ?

export class ExportFormComponent implements OnInit {

    public exportForm: FormGroup;

    constructor( private formBuilder: FormBuilder ) { }

    ngOnInit() {
        this.exportForm = this.formBuilder.group( {
            dataType: [''],
            items: this.formBuilder.array( [
                this.initItem(),
            ] )
        });
    }

    initItem() {
        return this.formBuilder.group( {
            exportExpression: [''],
            description: [''],
            updatable: [true],
            attributes: this.formBuilder.array( [
                this.initAttribute(),
            ] )
        });
    }

    initAttribute() {
        return this.formBuilder.group( {
            exportExpression: [''],
            localizedRawField: [''],
            localizable: [true],
        });
    }

    addItem() {
        const control = <FormArray>this.exportForm.controls['items'];
        control.push( this.initItem() );
    }

    removeItem( i: number ) {
        const control = <FormArray>this.exportForm.controls['items'];
        control.removeAt( i );
    }

    addAttribute() {

    }

    removeAttribute(  ) {

    }

    save( exportConfiguration: ExportConfiguration ) {
        console.log( exportConfiguration );
    }
}

My interface tree

export interface ExportConfiguration {
    dataType?: string,
    items?: Item[],
}

export interface Item {
    exportExpression?: string,
    description?: string,
    updatable?: boolean,
    attributes?: Attribute[],
}

export interface Attribute {
    exportExpression?: string,
    localizable?: boolean,
    localizedRawField?: string,
    rules?: TransformationRule[]
}

export interface TransformationRule {
    dataPathKey?: string,
    expressionCheck?: boolean,
    expression?: string,
}

EDIT

Okay so i used the demo posted as one of the answers but i get null in the following ( this.itemsCtrl.get( '${index}.attributes' ) as FormArray )

addAttribute( index: number ) {
        ( this.itemsCtrl.get( '${index}.attributes' ) as FormArray ).push( this.initAttribute() );
    }

解决方案

First of all I prefer to create references in component to handle the controls, instead of calling .controls or .get all the time.

So, your add's and remove's functions will be cleaner as your template.

It could be like this:

exportForm: FormGroup;
dataTypeCtrl: FormControl;
itemsCtrl: FormArray;

constructor(private formBuilder: FormBuilder) { }

ngOnInit() {
  this.dataTypeCtrl = this.formBuilder.control('');
  this.itemsCtrl = this.formBuilder.array([this.initItem()]);

  this.exportForm = this.formBuilder.group( {
      dataType: this.dataTypeCtrl,
      items: this.itemsCtrl
  });
}

// ...

addItem() {
  this.itemsCtrl.push(this.initItem());
}

removeItem(i: number) {
  this.itemsCtrl.removeAt(i);
}

addAttribute(index: number) {
  this.itemsCtrl.get(`${index}.attributes`).push(this.initAttribute())
}

removeAttribute(itemIndex: number, attrIndex: number) {
  this.itemsCtrl.get(`${itemIndex}.attributes`).removeAt(attrIndex)
}

Then, in template you can access directly the controls, as below:

...
<div formArrayName="items" *ngFor="let itemCtrl of itemsCtrl.controls; let i = index">
  <div [formGroupName]="i">
    <button (click)="removeItem(i)">Remove item</button>
    <input type="text" formControlName="description">
    <!-- other inputs from items -->

    <button (click)="addAttribute(i)">Add attribute</button>

    <div formArrayName="attributes" *ngFor="let attributeCtrl of itemCtrl.get('attributes').controls; let j = index">
      <div [formGroupName]="j">
        <button (click)="removeAttribute(i, j)">Remove attribute</button>
        <input type="text" formControlName="exportExpression"
        <!-- other inputs from attributes -->
      </div>
    </div>
  </div>
</div>

See DEMO

这篇关于Angular2 创建模型嵌套表单的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
相关文章
其他开发最新文章
热门教程
热门工具
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆