angular2中有没有一种方法可以根据设备选择模板

Is there a way in angular2 that a template is selected based on the device

我希望每个设备模板有 1 个用于 angular2 中的视图,对于某些视图,所有设备可能有 1 个。是否有可能基于浏览器用户代理

的angular2

有计划,但是否真正实施尚未决定。
目前,您可以使用媒体查询,例如 ngSwitch 来根据设备或屏幕尺寸显示视图的不同部分。

另见

您可以将 CSS @imports 与媒体查询一起使用。

您需要做的就是为每个设备创建一个单独的 CSS 文件,然后将其导入到您的模板样式中。

示例:

Angular2 组件:

@Component({
  selector: 'my-comp',
  template: `...`,
  styleUrls: ['./style.css']
})

style.css中:

@import url("device1.css") screen and (min-width: 300px);
@import url("device2.css") screen and (min-width: 800px);

然后是 device1.css 和 device2.css 中的设备特定样式。

有关 CSS @imports 的详细信息,请参阅 https://developer.mozilla.org/en/docs/Web/CSS/@import

另一种方法是使用 angular/flex-layout 包 与

fxHide API and fxShow API

示例

<div fxShow fxHide.xs="false" fxHide.lg="true"> ... </div>

当激活断点为:

  • xl,然后回退到默认的 fxShow;所以显示div
  • lg,那么div就隐藏了(因为值==='true')
  • md,然后回退到默认的 fxShow;因此显示 div
  • sm,然后回退到默认的 fxShow;所以显示div
  • xs,然后显示 div(因为值 === 'false')

这是带有断点的列表

或使用 ObservableMedia

例子

import {MediaChange, ObservableMedia} from "@angular/flex-layout";

const PRINT_MOBILE = 'print and (max-width: 600px)';

@Component({
   selector : 'responsive-component',
   template: `
      <div class="ad-content" *ngIf="media.isActive('xs')">
        Only shown if on mobile viewport sizes
      </div>
   `
})
export class MyDemo implements OnInit {
  constructor(public media: ObservableMedia) { }

  ngOnInit() {
    if (this.media.isActive('xs') && !this.media.isActive(PRINT_MOBILE)) {
       this.loadMobileContent();
    }
  }

  loadMobileContent() { /* .... */ }
}
  • print 和 (max-width: 600px) 是用于移动打印的 mediaQuery 视口大小。
  • xs 是与移动视口大小的 mediaQuery 关联的别名。