jvm
jvm

Reputation: 1712

Disable button click if input field is empty using angular 4

I have a search box and a search button. I need to disable button until user provides the search term, but the button gets disable always. I have following the code:

 <input type='text' [(ngModel)]='listFilter' />
 <button [disabled]="!listFilter" class="btn btn-primary"(click)='OnSearch(listFilter)'>
      Search
 </button>

What's wrong here? I'm using angular 4

Upvotes: 7

Views: 25007

Answers (3)

SRK
SRK

Reputation: 11

<input ref-filter type='text' [(ngModel)]='listFilter' />
<button class="btn btn-primary" [disabled]="listFilter === ''"(click)="ClearText()">Reset User</button>

TS:

listFilter='';
ClearText(){
this.listFilter='';

}

Upvotes: 1

Neo_Ryu
Neo_Ryu

Reputation: 121

You must use a template reference variable!

To do this, you can use either ref-prefix or #prefix. In your example, you will have to modify it like this:

<input ref-filter type='text' [(ngModel)]='listFilter' />
<button [disabled]="!filter.value" class="btn btn-primary" (click)='OnSearch(listFilter)'>
 Search 
</button>

A model reference variable (#varRef) is not the same as a model input variable (variable let), as you might see in a * ngFor. The scope of a reference variable is the entire model. Do not set the same variable name more than once in the same model. The execution value will be unpredictable.

Upvotes: 5

Anas
Anas

Reputation: 991

Add name property inside the input tag.

 <input type='text' [(ngModel)]='listFilter' name="listFilter"/>
            <button [disabled]="!listFilter" class="btn btn-primary" (click)='OnSearch(listFilter)'>Search</button>

Upvotes: 15

Related Questions