根据屏幕大小显示/隐藏多个 Div(Angular 2)

3

我希望使用一些按钮来使用angular2显示/隐藏多个div。

页面将最初显示所有div。当屏幕较小时,我会隐藏所有的div,并分别使用按钮显示特定的div,同时隐藏其他的div。

任何帮助都将不胜感激。

<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>

你自己用Angular 2尝试了什么?你发布的代码只有HTML。 - Roy
1个回答

4

使用@HostListenerresize事件来确定视口的宽度。然后在组件中分配一个具有此值的属性,您可以将其提供给HTML模板中的ngIf*

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>


非常感谢。如何显示特定 div 的点击事件 - sridharan
像这样:<div (click)="myFunction()">,然后在您的组件内定义 myFunction() - Chris Haugen

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接