I want to use some buttons to show/hide multiple divs using angular2
The page will initially show all divs. when the small screen i hide all div and then separate buttons to show a particular div while hiding the rest.
Any help would be much appreciated.
<div class="buttons">
<a class="button" id="showdiv1">Div 1</a>
<a class="button" id="showdiv2">Div 2</a>
<a class="button" id="showdiv3">Div 3</a>
</div>
<div class="row">
<div class="col-xlg-4 col-xl-5 col-lg-12 col-sm-12 col-xs-12 hidden-sm-down">
</div>
<div class="col-xlg-4 col-xl-5 col-lg-12 col-sm-12 col-xs-12 hidden-sm-down">
</div>
<div class="col-xlg-4 col-xl-5 col-lg-12 col-sm-12 col-xs-12 hidden-sm-down">
</div>
</div>
Use @HostListener
along with the resize
event to determine the viewport's width. Then set assign a property with this value in your component which you can then supply to an ngIf*
in your HTML template.
import { Component, HostListener, AfterViewInit } from '@angular/core';
@Component()
export class AppComponent {
windowWidth: number = window.innerWidth;
//initial values, The window object may still be undefined during this hook, let me know if that's the case and we'll figure out a better hook for the initial value
ngAfterViewInit() {
this.windowWidth = window.innerWidth;
}
//if screen size changes it'll update
@HostListener('window:resize', ['$event'])
resize(event) {
this.windowWidth = window.innerWidth;
}
}
<!-- Then any HTML element you wish to toggle apply the *ngIf directive as so: -->
<div *ngIf*="windowWidth > 800">content</div>