【问题标题】:Angular clear input with [ngAutonumeric] directive使用 [ng Autonumeric] 指令的角度清除输入
【发布时间】:2019-09-05 16:11:34
【问题描述】:

我在 Angular 项目中工作,我使用反应形式,并且我对某些输入使用 [ngAutonumeric] 指令,我的问题是:我无法清除包含该指令的输入

我有一个这样的表单组:

// 其他表单控件..

dataFormGoup : this.fb.group({
        id : [],
        firstanme: [''],
        lasName: [''],
        amount: ['']
})

在我的 html 代码中:

<input matInput [ngAutonumeric]="{digitGroupSeparator: ' ', decimalCharacter: ',', decimalCharacterAlternative: '.',
                            currencySymbol: '\u00a0€',
                            currencySymbolPlacement: 's',
                            roundingMethod: 'U',
                            minimumValue: '0'
                          }"  formControlName='amount'>

并且我有一个要清除表单组的函数,我使用此代码清除所有输入,但输入“金额”仍不为空。

这是我的代码:

//some code..

    this.globalForm.get('dataFormGoup').reset();

我也尝试了这段代码,但不起作用

this.globalForm.get('dataFormGoup').get('amount').reset();

this.globalForm.get('creditDocumentaireDetailGroup').patchValue({
   amount: ''
});

当我删除指令 [ngAutonumeric] 我的代码运行良好时,您有什么建议可以解决这个问题。

提前致谢。

【问题讨论】:

标签: angular angular-reactive-forms


【解决方案1】:

您不能将 ngAutonumeric 输入的值设置为 null,而 reset 函数就是这样做的,基本上要清除该输入,您必须将其值设置为 0

例子:

import { Component } from '@angular/core';
import { FormBuilder } from '@angular/forms'

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  dataFormGoup: any;
  constructor(private fb: FormBuilder) {
    this.dataFormGoup = this.fb.group({
      id: ['', []],
      firstanme: ['', []],
      lasName: ['', []],
      amount: ['', []]
    })
  }

  clearAmountField() {
    this.dataFormGoup.get('amount').patchValue(0) // this should do the trick.
  }
}
<form [formGroup]="dataFormGoup">
    <input [ngAutonumeric]="{digitGroupSeparator: ' ', decimalCharacter: ',', decimalCharacterAlternative: '.',
                            currencySymbol: '\u00a0€',
                            currencySymbolPlacement: 's',
                            roundingMethod: 'U',
                            minimumValue: '0'}" formControlName='amount'>
    <input formControlName='id' placeholder="id" >
    <input formControlName='firstanme' placeholder="firstanme" >
    <input formControlName='lasName' placeholder="lasName" >
</form>

<button (click)="clearAmountField()">clear</button>

【讨论】:

  • 您好 @Ahmed 感谢您的回复,但 patchvalu(0) 不起作用。
猜你喜欢
  • 2015-09-01
  • 1970-01-01
  • 2018-09-28
  • 1970-01-01
  • 2018-02-14
  • 1970-01-01
  • 1970-01-01
  • 2019-05-06
  • 1970-01-01
相关资源
最近更新 更多