Boosman
Boosman

Reputation: 197

Uncheck checkbox on text input & clear text input when checkbox is checked

I have a search bar and check box as so:

<input type="text" placeholder="Search..." (keyup)="onKey()" [(ngModel)]="input">
<input type="checkbox" (click)="clearSearch()" [(ngModel)]="checkbox">View All

Whenever anyone types into the search bar I want the checkbox to become unchecked. Likewise, whenever anyone checks the checkbox, I want the search bar to be cleared.

I've tried the following:

export class App {
 checkbox = ['checked']
 clearSearch() { 
 this.input = '';
};
onKey() { 
 checkbox = ['unchecked']
}

But it obviously doesn't quite work.

Here is a plunker with the above code: https://plnkr.co/edit/uAYxswpoz18jlRUqAMn5?p=preview

Which is the best way to achieve this functionality?

Thanks!

Upvotes: 4

Views: 1537

Answers (2)

Sajeetharan
Sajeetharan

Reputation: 222532

In your function make this.checkbox to be false.

 <input type="checkbox" (click)="clearSearch()" [(ngModel)]="checkbox">View All

your function

 onKey() { 
     this.checkbox = false;
  }

DEMO

Upvotes: 1

Kasper Ziemianek
Kasper Ziemianek

Reputation: 1349

You were almost there. First of all, I advice You to use boolean values for checkboxes data models. Array evaluates to true so checkbox is still checked. If you reference instance properties, You should reference them by using word this. So the method onKey() should be :

onKey() { 
 this.checkbox = false
}

plunker

Upvotes: 2

Related Questions