Show Hide a div in angular 7
Asked Answered
X

7

22

I am trying to show/hide a div in angular 7 using ng-model and ng-hide but its not working.

button to Show/Hide- used ng-model to set expression

    <button type="checkbox" ng-model="show" >show/hide</button>

div to Show/Hide, Used ng-hide to hide the div

<div class="row container-fluid" ng-hide="show" id="divshow" >
  Div Content
</div>    
</body>
</html>

I have tried ng-model and ng-hide still it's not working. Please provide a solution

Xanthic answered 27/3, 2019 at 10:30 Comment(2)
Possible duplicate of What is the equivalent of ngShow and ngHide in Angular?Croix
Please provide a minimal reproducible exampleEndowment
U
22

In your HTML

<button (click)="toggleShow()" type="checkbox" >show/hide</button>

<div *ngIf="isShown" class="row container-fluid"  id="divshow" >
Div Content

</div>

in your component class add this:

isShown: boolean = false ; // hidden by default


toggleShow() {

this.isShown = ! this.isShown;

}
Unprepared answered 27/3, 2019 at 10:38 Comment(0)
W
14

Try this solution:

Solution 1:

<div *ngIf="show" class="row container-fluid"  id="divshow" >
        Div Content
    </div>

Solution 2:

<div [hidden]="!show" class="row container-fluid"  id="divshow" >
            Div Content
        </div>
Willey answered 27/3, 2019 at 10:36 Comment(1)
There is a big difference between the two. ngIf removes and creates the element. [hidden] no.Bitartrate
C
5

You can use <div *ngIf="show"

and use in your .ts file a boolean that you can change the value if the button is tiggered

Calender answered 27/3, 2019 at 10:34 Comment(0)
E
3

You can use change event handler if you are using type='checkbox'

<input type="checkbox" (change)="show = !show" ng-model="show" />
Div to Show/Hide

<div class="row container-fluid" *ngIf="show" id="divshow" >
Div Content
</div>

Stackblitz Demo

Emetine answered 27/3, 2019 at 10:51 Comment(1)
I can ask you a question concerning your code?Swanner
H
1

Best Possible Way :

<input type="checkbox" (change)="show = !show" ng-model="show"/>
show/hide

<div class="row container-fluid" [hidden]="!show" id="divshow" >
Div Content
</div>
Howund answered 8/3, 2021 at 8:22 Comment(0)
F
0

Here is a neat way to hide/remove items, specially handy if there is a list of items.

Note how it takes advantage of Angular's template variables (#ListItem).

<ng-container *ngFor="let item of list">
  <div #ListItem>
    <button (click)="close(ListItem)">
  </div>
</ng-container>
  close(e: HTMLElement) {
    e.remove();
  }
Flavius answered 23/3, 2021 at 19:48 Comment(0)
C
-1

you should use a flag In your ts file, By default flag false

<button type="checkbox" (click)="flag= !flag">{{falg=== true ? 'Show' : 'Hide'}}</button>
Commentative answered 27/3, 2019 at 10:38 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.