Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular 2 : Toggle Boolean based on a condition

I have a search-bar and I want to show all the filtered names when the input value length is 2 or longer.

I managed to get the value.length out of the input field. Now I'm stuck. At first I had done:

if (value.length >= 2){
  showNames: true;
} 

Default showNames is false. And when the length was 2 or higher, it set to true. So, that's working. Only when the user erases the text, so the value.length is below 2 again, the boolean won't turn false again. I tried if else, but I know that's not correct in Angular 2.

<ion-searchbar (ionInput)="getNames($event)"></ion-searchbar>
<ion-list *ngIf="showNames">
   <ion-item *ngFor="let name of names">
     {{ name }}
   </ion-item>
</ion-list>

I know I can toggle a boolean from a button click, but I just want to toggle it from the length of a value.

*ngIf="value.length >= 2" doesn't work either, because I create the variable 'value' in my Typescript. So in my HTML it's not defined. And I don't want to use the big formula to calculate the length, that's why I created a variable.

How can I either

  1. Pass the variable 'value' from my Typescript to my HTML so I can use the *ngIf="value.length > 2"?
  2. OR do some kind of If / Else in my Typescript, so I can use a single boolean like *ngIf="showNames" in my HTML?
like image 610
J.DD Avatar asked Aug 08 '26 09:08

J.DD


1 Answers

You can bind to the model of the searchbar like this:

<ion-searchbar [(ngModel)]="searchValue" (ionInput)="getNames($event)"></ion-searchbar>
<ion-list *ngIf="searchValue.length >= 2">
   <ion-item *ngFor="let name of names">
     {{ name }}
   </ion-item>
</ion-list>

And in your component define such a variable:

export class ComponentA {
    searchValue: string = "";

    // ...
}
like image 130
rinukkusu Avatar answered Aug 10 '26 23:08

rinukkusu



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!