简体   繁体   English

按钮显示为禁用,直到我在 Angular 中点击输入

[英]Button appears disabled until i click out of input in Angular

I have a form (heat index calculator) which take 2 inputs, dropdown and button, button is disabled if there is nothing in the inputs or if the inputs are invalid, everything works fine except when i type in both inputs valid arguments the button still appears disabled until i click out of the input.我有一个表格(热指数计算器),它接受 2 个输入,下拉菜单和按钮,如果输入中没有任何内容或输入无效,则按钮将被禁用,一切正常,除非我输入两个输入有效参数时按钮仍然显示禁用,直到我点击输入。 Is there way to enable the button as soon as i type valid argument in the input without having to click out of it to show?有没有办法在输入中键入有效参数后立即启用按钮,而无需单击它来显示? and another similar issue is.. i have dropdown there with celsius and fahrenheit options, when selected F the minimum value user have to type is 80 and for C minimum is 26 and the issue is when i choose C for eg and type 50 and change my mind and select fahrenheit instead, the validation error doesnt show up.. i have to delete the value and if i type again the 50 now the error shows and another similar issue is.. i have dropdown there with celsius and fahrenheit options, when selected F the minimum value user have to type is 80 and for C minimum is 26 and the issue is when i choose C for eg and type 50 and change我的想法是选择华氏温度,验证错误没有出现。我必须删除该值,如果我再次输入 50,现在错误显示

this is html这是 html

<form [formGroup]="heatIndexForm" class="wrapper" (ngSubmit)="onSubmit()">
    <label class="temperature-row">
      <p class="temperature-input">Air Temperature</p>
      <div class="field col-12 md:col-4">
        <p-inputNumber
        [style]="{'height': '51px'}"
        formControlName="temperature"
        mode="decimal"
        class="form-control">
      </p-inputNumber>
      <div class="validation-error" *ngIf="temperatureValidationFahrenheit">Temperature must be 80&deg;F or higher!</div>
      <div class="validation-error" *ngIf="temperatureValidationCelsius" >Temperature must be 26&deg;C or higher!</div>
    </div>
      <p-dropdown
      class="form-control"
      [style]="{'height':'51px', 'paddingTop': '5px', 'marginLeft': '5px'}"
      formControlName="selectedTemp"
      (onChange)="selectionChanged()" [options]="temps"
      optionLabel="units"></p-dropdown>
    </label>
    <label class="humidity-row">
      <p class="humidity-input">Relative Humidity</p>
      <div [style]="{'position': 'relative'}" class="field col-12 md:col-4">
        <p-inputNumber   [style]="{'height': '51px'}" mode="decimal"formControlName="humidity" class="form-control"></p-inputNumber>
        <div class="percent">%</div>
        <div  class="validation-error" *ngIf="heatIndexForm.controls['humidity'].invalid">Humidity must be 0% - 100%</div>
      </div>
    </label>
    <div class="buttons">
      <button
      class="form-control"
      [disabled]="disableCalculateButton"
       pButton
       label="Calculate"></button>
      <p-button label="Reset" (onClick)="reset()"></p-button>
    </div>
  </form>

form ts表格

export class HeatIndexComponent implements OnInit {
  haveResult: boolean = false;
  temps: Temperature[];
  heatIndexForm: FormGroup;

  constructor(
    private heatIndexService: HeatIndexService,
    private localStore: LocalService
  ) {
    this.temps = [
      new Temperature('Celsius', 'C'),
      new Temperature('Fahreheit', 'F'),
    ];
  }

  ngOnInit(): void {
    this.heatIndexForm = new FormGroup({
      temperature: new FormControl(null, Validators.min(26)),
      humidity: new FormControl(null, [Validators.max(100), Validators.min(0)]),
      selectedTemp: new FormControl(new Temperature('Celsius', 'C')),
      result: new FormControl(''),
      resultComment: new FormControl(''),
    });
  }

  get temperatureValidationFahrenheit() {
    return (
      this.heatIndexForm.controls['selectedTemp'].value.code === 'F' &&
      this.heatIndexForm.controls['temperature'].invalid
    );
  }

  get temperatureValidationCelsius() {
    return (
      this.heatIndexForm.controls['selectedTemp'].value.code === 'C' &&
      this.heatIndexForm.controls['temperature'].invalid
    );
  }

  get disableCalculateButton() {
    return (
      this.heatIndexForm.controls['temperature'].invalid ||
      this.heatIndexForm.controls['humidity'].invalid ||
      this.heatIndexForm.controls['temperature'].value == null ||
      this.heatIndexForm.controls['humidity'].value == null
    );
  }

  selectionChanged() {
    this.haveResult = false;
    const value = this.heatIndexForm.get('selectedTemp').value;
    this.heatIndexForm.controls['temperature'].clearValidators();
    if (value.code !== 'C') {
      this.heatIndexForm.controls['temperature'].setValidators(
        Validators.min(80)
      );
    }
    if (value.code === 'C') {
      this.heatIndexForm.controls['temperature'].setValidators(
        Validators.min(26)
      );
    }
    this.heatIndexForm.updateValueAndValidity();
  }

i tried the button issue with template driven approach but same thing happened我用模板驱动方法尝试了按钮问题,但同样的事情发生了

To enable and disable submit button as soon as you type, let angular validate the form for you instead of providing your own validator method disableCalculateButton() .要在您键入后立即启用和禁用提交按钮,请让 Angular 为您验证表单,而不是提供您自己的验证器方法disableCalculateButton() Add Validators.required to temperature and humidity fields (instead of manually checking if they're null):Validators.required添加到temperaturehumidity字段(而不是手动检查它们是否为空):

component.ts组件.ts

temperature: new FormControl(null, [Validators.min(26), Validators.required]),
humidity: new FormControl(null, [Validators.max(100), Validators.min(0), Validators.required]),

And change [disabled] value in submit button.并更改提交按钮中的[disabled]值。 to only display error message when field is populated, check if the form field has been touched仅在填充字段时显示错误消息,检查表单字段是否已被touched

component.html组件.html

<div class="validation-error" *ngIf="temperatureValidationFahrenheit && 
heatIndexForm.controls.temperature.touched">
          Temperature must be 80&deg;F or higher!
</div>
<div class="validation-error" *ngIf="temperatureValidationCelsius && 
heatIndexForm.controls.temperature.touched">
          Temperature must be 26&deg;C or higher!
</div>
.
.
.
<div
class="validation-error"
*ngIf="heatIndexForm.controls['humidity'].invalid &&
 heatIndexForm.controls.humidity.touched">
          Humidity must be 0% - 100%
</div>
.
.
.
<button
    class="form-control"
    [disabled]="heatIndexForm.invalid"
    pButton
    label="Calculate">
submit
</button>

Link to stackblitz链接到堆栈闪电战

For your second issue unfortunatly I couldn't find any solution but I think defining a custom validator would help alot.不幸的是,对于你的第二个问题,我找不到任何解决方案,但我认为定义一个自定义验证器会有很大帮助。 Manging multiple error messages for one field with *ngIf is a bit of trouble.使用*ngIf为一个字段管理多个错误消息有点麻烦。

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

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