使用角度设备检测器服务为平板电脑隐藏按钮

时间:2019-04-30 20:55:52

标签: angular typescript

我试图仅使用角度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>

角度服务

@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();
  }

}

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

1 个答案:

答案 0 :(得分:1)

将服务注入您的组件

sample.component.ts

constructor(private exampleDeviceDetectorService: ExampleDeviceDetectorService) {}

使用* ngIf从DOM中删除元素

sample.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中的元素

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