首页 > 解决方案 > 使用角度设备检测器服务隐藏平板电脑的按钮

问题描述

我正在尝试仅使用角度 ngx 设备检测器服务在平板电脑上隐藏一个元素。

我已经使用 css 媒体查询完成了这项工作。但是,我想看看是否可以使用 ngx 设备检测器获得相同的结果。

html

<div id="hide-download">
          <app-button name="download" classAttr="btn-primary" (click)="downloadFile()" [disabled]="!allOrders || allOrders.length === 0">
              <i class="fas fa-download button-icon-padding"></i>
              Download
          </app-button>

Angular 服务 ts

@Injectable()
export class ExampleDeviceDetectorService {

  public deviceInfo: any;
  public isMobile: any;
  public isTablet: any;
  public isDesktop: any;

  constructor(
    public deviceService: DeviceDetectorService
  ) {
    this.getDeviceInfo();
  }

  getDeviceInfo() {
    this.deviceInfo = this.deviceService.getDeviceInfo();
    this.isMobile = this.deviceService.isMobile();
    this.isTablet = this.deviceService.isTablet();
    this.isDesktop = this.deviceService.isDesktop();
  }

}

我预计该按钮不会显示在平板电脑设备上。

标签: angulartypescript

解决方案


将服务注入到您的组件中

样本.component.ts

constructor(private exampleDeviceDetectorService: ExampleDeviceDetectorService) {}

使用 *ngIf 从 DOM 中删除元素

示例.component.html

<div id="hide-download" *ngIf="!exampleDeviceDetectorService.isTablet">
    <app-button name="download" classAttr="btn-primary" 
    (click)="downloadFile()" [disabled]="!allOrders || allOrders.length === 0">
        <i class="fas fa-download button-icon-padding"></i>
            Download
    </app-button>
</div>

使用 [hidden] 从 DOM 中隐藏元素

示例.component.html

<div id="hide-download" [hidden]="!exampleDeviceDetectorService.isTablet">
    <app-button name="download" classAttr="btn-primary" 
    (click)="downloadFile()" [disabled]="!allOrders || allOrders.length === 0">
        <i class="fas fa-download button-icon-padding"></i>
            Download
    </app-button>
</div>

推荐阅读