【问题标题】:Disable Reactive Form's Input Fields禁用响应式表单的输入字段
【发布时间】:2021-07-28 08:52:35
【问题描述】:

图片显示了我的表单域的显示方式。我想知道当用户输入“折扣百分比”及其相关的“备注”时禁用休息表单输入字段的最佳方法是什么。

Ex 1:- 如果用户在 Discount Percentage 字段中输入,则 Discount Amount、Additional Loading Percentage 和 Additional Loading amount 及其相关的 Remark 字段将被禁用。

Ex 2:- 如果用户在 Additional Loading Amount 字段中输入,则 Discount Amount、Additional Loading Percentage 和 Discount Percentage 及其相关的 Remark 字段将被禁用。

如果用户清除输入字段,则应再次启用禁用的输入字段。

    formGroup = new FormGroup({
        discountPercentage: new FormControl(),
        discountPercentageRemark: new FormControl(''),
        discountAmount: new FormControl(),
        discountAmountRemark: new FormControl(''),
        loadingPercentage: new FormControl(),
        loadingPercentageRemark: new FormControl(''),
        loadingAmount: new FormControl(),
        loadingAmountRemark: new FormControl('')
  })

【问题讨论】:

  • 请传递您的 HTML 代码

标签: angular angular-reactive-forms formgroups


【解决方案1】:

您可以订阅ngOnInit中discountPercentage字段的变化,并据此设置模板的disable属性;

ngOnInit() {
  this.formGroup.get('discountPercentage').valueChanges.subscribe((value) => {
  if(value) {
     this.isDiscountPercantageHasValue = true;
    } else {
     this.isDiscountPercantageHasValue = false;
    }
  })
}

在你的模板文件中你可以像下面这样设置它;

<input type="text" formControlName="discountAmount" [disabled]="isDiscountPercantageHasValue" .../>

【讨论】:

  • 那么如何禁用表单相关的表单域呢?否则,您将验证器设置为必需。我不需要那个选项。
  • 哎呀!我的错。更新了我的答案。
猜你喜欢
  • 1970-01-01
  • 2017-08-07
  • 2020-01-06
  • 2014-09-03
  • 1970-01-01
  • 2019-04-01
  • 2012-07-07
  • 2021-10-04
  • 2018-01-28
相关资源
最近更新 更多