angular - 单击添加按钮将行添加到表中,新行是每个单元格中的表单字段

标签 angular angular-reactive-forms angular-forms

实际上,在添加单击时,我需要添加行,但我无法获取 ngmodel 对象,或者是否有其他最佳方法来使用响应式(Reactive)表单来实现,所以最后的要求是在添加单击时获取一行并获取表单值的最佳实现方式或者请修改上面的代码

Stackblitz Link

最佳答案

在此处查看现场演示。

http://keepnote.cc/code/form-group-with-formarray-adding-dyamic-row-angular-5-6

请检查一下。

我们必须使用 FormBuilderFormBuilder.array 来处理动态行。

html

<form [formGroup]="carForm" (ngSubmit)="saveIntergration()">
    <div formArrayName="details" class="form-group" *ngFor="let field of carForm.get('details').controls; let ind = index;">
        <div [formGroupName]="ind">
            Type:
            <input type="text" formControlName="type">

            model:
            <input type="text" formControlName="model">

            year:
            <input type="text" formControlName="year">

            make:
            <input type="text" formControlName="make">

            color
            <input type="text" formControlName="color">

            plateNumber
            <input type="text" formControlName="plateNumber">

            <hr>
        </div>
    </div>
</form>

<button (click)="addRow()">Add New</button>

<pre>
    {{carForm.value | json}}
</pre>

ts

import { Component, ViewChild } from '@angular/core';
import { FormBuilder, FormGroup, FormControl, Validators, FormArray } from '@angular/forms';

@Component({
selector: 'app-root',
templateUrl: './app.component.html'

})
export class AppComponent {
    public carForm: FormGroup;
    constructor(private fb: FormBuilder) {

        const items = [];
        items.push(this.fb.group({
            type: [],
            model: [],
            year: [],
            make: [],
            color: [],
            plateNumber: []
        }));

        this.carForm = this.fb.group({
            details: this.fb.array( items )
        });
    }

    addRow() {
        const details = this.carForm.get('details') as FormArray;
        details.push(this.createItem());
    }

    createItem(): FormGroup {
        return this.fb.group({
            type: [],
            model: [],
            year: [],
            make: [],
            color: [],
            plateNumber: []
        });
    }
}

关于angular - 单击添加按钮将行添加到表中,新行是每个单元格中的表单字段,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53513269/

相关文章:

当表单域处于事件状态时,Angular Material 表单域轮廓输入颜色会发生变化

Angular4向导第一个文本字段专注于下一步

angular - writeValue 在自定义表单控件中具有无效值

angular - 将一组字段动态添加到响应式(Reactive)表单

forms - 形式中的形式。表单控件可以继承吗?

javascript - ng-repeat 内的 ng-form 不更新子表单。$subscribed

angular - 身份验证 - VS 2017 15.3; ASP.Net Core 2.0; Angular

Angular Material 卡片阴影颜色

angular - 如何将 Highcharts 渲染为以 id 作为容器的 div - Angular?

javascript - Validators.pattern 未显示手机号码错误