StillLearningToCode
StillLearningToCode

Reputation: 2461

Angular2 hiding output if empty

I have the code as shown bellow that gets some data from a REST endpoint and displays it in a list. The page loads fine and when input is entered into the textbox everything works as planned. the issue is if a user removes all input from the text box the output the output remains. is there anyway to use ngIf to say if searchRes is is empty then don't show anything? I tried to use *ngIf="searchRes.length > 0 but there was no change, the old output still got diplayed...

<div class="row">
<div class="col-md-12">
  <form>
  <div class="form-group">
    <div class="input-group">
      <span class="input-group-addon">&gt;&gt;</span>
      <input type="text"
             class="form-control" [(ngModel)]="searchStr" name="searchStr" (keyup)="searchWord()">
      <span class="input-group-btn"></span>
    </div>
  </div>
</form>
</div>
</div>

<div *ngIf="searchRes" class="search-res well">
<div *ngFor="let res of searchRes">
<div class="row">
  <div class="col-md-12">
    <p>{{res}}</p>
  </div>
</div>
</div>
</div>

Upvotes: 3

Views: 1913

Answers (2)

ranakrunal9
ranakrunal9

Reputation: 13558

If you want to hide div with class search-res well when there is no value in text box then you can use <div *ngIf="searchStr" class="search-res well"> or you can make searchRes = [] in your component searchWord method by checking searchStr value is empty or not.

Upvotes: 0

Atal Kishore
Atal Kishore

Reputation: 4758

when user removes all input from the text box just make searchRes empty in the component ( if you have other textboxes other than searchStr)

searchRes=[];

and in the html use

<div *ngIf="searchRes && searchStr" class="search-res well">

and your code will work fine

Upvotes: 1

Related Questions