简体   繁体   中英

angular button disable when form control empty

I need to disable search button, when text-box empty. I tried to add disable attribute to search button. but its not working.

This is my html code:

<div class="col-md-5 pl-0">
  <div class="input-group mb-3">
    <input
      type="text"
      placeholder="Enter MTCN Number"
      maxlength="16"
      class="form-control mtcn-textbox"
      [formControl]="mtcn"
      required
      type="text"
      aria-describedby="basic-addon2"
    />
    <div class="input-group-append">
      <button
        class="btn btn-primary"
        type="button"
        (click)="retrieveData()"
        [disabled]="mtcn"
      >
        Search
      </button>
    </div>
  </div>
</div>

Can someone help me to achieve this?

You can disable your button just using [disabled]="!mtcn.value" . Or you can disable button if your form is not valid: [disabled]="!myForm.valid"

您可以尝试 [disabled]="!mtcn.value" 或将您的代码放入 Form 标签并为其指定一个 id 并使用“form.valid”

Please note that mtcn is a FormControl, which is always truthy. You want to check the value of the FormControl.

You have 2 possibilities.

1. disabled attribute

<div class="input-group mb-3">
  <input type="text" placeholder="Enter MTCN Number" maxlength="16" class="form-control mtcn-textbox" [formControl]="mtcn" required type="text" aria-describedby="basic-addon2">
  <div class="input-group-append">
    <button class="btn btn-primary" type="button" (click)="retrieveData()" [disabled]="!mtcn.value">Search</button>
  </div>
</div>

2. disabled class (since it seems you are using bootstrap)

<div class="input-group mb-3">
  <input type="text" placeholder="Enter MTCN Number" maxlength="16" class="form-control mtcn-textbox" [formControl]="mtcn" required type="text" aria-describedby="basic-addon2">
  <div class="input-group-append">
    <button class="btn btn-primary" type="button" (click)="retrieveData()" [ngClass]="{ disabled: !mtcn.value }">Search</button>
  </div>
</div>

The [disabled]="!mtcn.value" would work, but I'd like to strongly advise against it. Assume you want to add some other validation rules (length, pattern, whatever) - you'd need to repeat the same thing twice, in the form control itself and in the button. In the long run, it'll get tedious to maintain and invite bugs.

Just go

<button [disabled]="mtcn.invalid">

Edit: Oh, and if you're using [formControl] , put the validation rules in the mtcn definition in the TypeScript, not in the template, right now you're mixing model driven and template driven forms.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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