简体   繁体   English

在Angular 2中,反应式不会使用ngModel和formArrayName更新值

[英]In Angular 2 reactive form doesn't update values using ngModel and formArrayName

I have a simple Reactive Form in Angular 2 and my form doesn't detect change of cells of a primeng data table. 我在Angular 2中有一个简单的Reactive Form,并且我的表单无法检测到primeng数据表的单元格更改。 The html is: 的HTML是:

<form [formGroup]="myForm" novalidate (ngSubmit)="onSubmit()">
<p-dataTable [value]="dataMenu" [editable]="true" formArrayName="menu">
    <p-column field="menu" header="Menu"></p-column>
    <p-column field="price" header="Price" [editable]="true">
        <template let-row="rowData" let-i="rowIndex" pTemplate="body">
            {{row.price}}
        </template>
        <template let-row="rowData" let-i="rowIndex" pTemplate="editor">
            <input type="number" pInputText [(ngModel)]="row.price" name="test" [ngModelOptions]="{standalone: true}"/>
        </template>
    </p-column>
</p-dataTable>

and the .ts file is: .ts文件是:

this.myForm = this.fb.group( { //fb is FormBuilder
    menu: this.fb.array([]),
});

this.setDataMenu(this.dataMenu);
...
setDataMenu( menu: Array<any> ) {
    const control = <FormArray>this.myForm.controls['menu'];
    for ( let m of menu ) {
        control.push( this.fb.control(m, validatePrices) );
    }
}

function validatePrices( c: FormControl ) {

    return ( c.value != null && c.value.price) ? null : {
        validatePrices: {
            valid: false
        }
    };
}

The problem is that the validation fires only at the beginning and when the value of "dataMenu" changes, the form does not detect this change. 问题是验证仅在开始时触发,并且当“ dataMenu”的值更改时,表单不会检测到此更改。

Not sure why you would want to use two-way binding, [(ngModel)] with Reactive Forms? 不确定为什么要在[(ngModel)]式表单中使用双向绑定[(ngModel)]

You should use the formControlName attribute with your input tag. 您应该在input标签中使用formControlName属性。

Example : 范例:

Create your form 建立表格

this.myForm = this.fb.group( { //fb is FormBuilder
    menu: this.fb.array([]),
});

Subscribe to the formGroup or individual controls to listen for values. 订阅formGroup或单个控件以侦听值。

this.myForm.get('menu').valueChanges(val => this.menuValue = val);

In your template make this simple change. 在您的模板中进行此简单更改。

<input type="number" pInputText formControlName="menu" name="test" [ngModelOptions]="{standalone: true}"/>

As you can see I have removed [(ngModel)] and added formControlName instead. 如您所见,我删除了[(ngModel)]并添加了formControlName

Validation 验证方式

You can then easily validate changes made to the controls. 然后,您可以轻松地验证对控件所做的更改。 One simple method would be to just pass the val returned from the subscription callback into a validation method. 一种简单的方法是将订阅回调返回的val传递给验证方法。

The preferred approach would be to use ValidatorFn though 首选方法是使用ValidatorFn

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM