因此,您可以使用以下可用数据来检测用户是否在桌面/平板电脑/移动设备上导航器用户代理 https://www.w3schools.com/jsref/prop_nav_useragent.asp.
您可以编写自己的 Angular 服务来执行此操作,但简单的解决方案是使用诸如ngx-设备检测器 https://www.npmjs.com/package/ngx-device-detector。它提供了一项服务(使用navigator.userAgent
在引擎盖下),您可以将其注入到组件中以检测用户正在运行的设备/平台。
您可以在组件中使用它,例如:
constructor(private deviceService: DeviceDetectorService) {}
isMobile = this.deviceService.isMobile();
然后在你的模板中:
<div *ngIf="isMobile">I only appear on mobile</div>
更好的方法是将其包装在指令中,这样您就不必在许多组件中重复此代码。
import { Directive, OnInit, TemplateRef, ViewContainerRef } from '@angular/core';
@Directive({
selector: '[isMobile]'
})
export class IsMobileDirective implements OnInit {
constructor(private deviceService: DeviceDetectorService,
private templateRef: TemplateRef<any>,
private viewContainer: ViewContainerRef) { }
ngOnInit() {
if (this.deviceService.isMobile()) {
this.viewContainer.createEmbeddedView(this.templateRef);
} else {
this.viewContainer.clear();
}
}
}
现在,您只需在组件模板内的任何元素上使用此指令即可轻松渲染基于设备的内容(请注意,此结构指令需要星号):
<div *isMobile>I only appear on mobile</div>
同样你也可以创建isDesktop
, isTablet
, isNotMobile
根据需要指示。