如何使用angular2一键单击后禁用按钮

时间:2018-06-22 06:00:58

标签: javascript angular typescript

我有一个发送按钮,其中包含2个Api。 因此,如果输入框为空,则发送按钮被禁用。 现在我想要一种条件, 提供电子邮件ID并单击“保存”按钮后,单击一次必须禁用它。 如果我再次在输入框上进行编辑,则必须将其启用或必须处于禁用状态。

3 个答案:

答案 0 :(得分:1)

您只能为此使用HTML:

<button
  #submitButton
  (click)="generateEmailOtp(enterSms,enterEmail); submitButton.disabled = true;"
  class="btn pull-right otp"
  *ngIf="isConfirmEmailOtp || isSms">Send OTP</button>

输入更改后再次启用:

<input
  class="form-control col-lg-12" 
  type="email" 
  [(ngModel)]="enterEmail"
  name="myEmail"
  #myEmail="ngModel"
  email
  pattern="[a-zA-Z0-9.-_]{1,}@[a-zA-Z.-]{2,}[.]{1}[a-zA-Z]{2,}"
  (input)="submitButton.disabled = false"
  #emailOTP>

答案 1 :(得分:0)

如果您使用的是反应形式,请查看此stackblitz

component.ts

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  public form: FormGroup;
  public isThePreviousEmail: boolean;

  private previousEmail: string;

  constructor(private fb: FormBuilder) {
    this.isThePreviousEmail = true;
    this.buildForm();
    this.form.valueChanges.subscribe((value) => {
      if (this.previousEmail) {
        this.isThePreviousEmail = value !== this.previousEmail;
      }
    });
  }

  public onSubmit(): void {
    this.previousEmail = this.form.value.email;
    this.isThePreviousEmail = false;
  }

  private buildForm(): void {
    this.form = this.fb.group({
      email: [null, Validators.compose([Validators.required, Validators.email])]
    });
  }
}

component.html

<form [formGroup]="form" (submit)="onSubmit()">
    Email: <input formControlName="email">

    <button type="submit" [disabled]="form.get('email').invalid || !isThePreviousEmail">Submit</button>
</form>.

我正在使用动态表单验证来禁用“提交”按钮。一个布尔变量,当用户编辑输入字段时该变量将变为假。

[disabled]="form.get('email').invalid || !isThePreviousEmail"

我正在订阅这样的表单值更改。

this.form.valueChanges.subscribe((value) => {
          if (this.previousEmail) {
            this.isThePreviousEmail = value !== this.previousEmail;
          }
});

然后在onSubmit方法中,将值设置为previousEmail并将isThePreviousEmail设置为false。

public onSubmit(): void {
    this.previousEmail = this.form.value.email;
    this.isThePreviousEmail = false;
  }

这可以帮助您了解一个想法。

答案 2 :(得分:0)

检查

<button (click)="generateEmailOtp(enterSms,enterEmail)" class="btn pull-right otp" [disabled]="buttonDisabled">Some Button</button>

buttonDisabled: boolean = false; //class variable
generateEmailOtp(enterSms,enterEmail) {
    this.buttonDisabled = !this.buttonDisabled

    // TO DO

    // If any error/valdiation fails, again reset this.buttonDisabled = !this.buttonDisabled
}