【发布时间】:2018-10-09 22:50:58
【问题描述】:
假设我们有几个组件,每个组件都应具有不同的布局/用户界面(模板),并以显示尺寸为条件。
我的解决方案是创建这样一个组件:
import {Component} from '@angular/core';
import {BreakpointObserver, Breakpoints} from '@angular/cdk/layout';
@Component({
selector: 'ui-switcher',
template: `
<ng-content *ngIf="isSmall" select="mobile"></ng-content>
<ng-content *ngIf="!isSmall" select="web"></ng-content>
`
})
export class UiSwitcherComponent {
public isSmall: boolean;
constructor(breakpointObserver: BreakpointObserver) {
breakpointObserver.observe([Breakpoints.Small, Breakpoints.XSmall]).subscribe(result => {
this.isSmall = result.matches;
});
}
}
并以这种方式使用它:
<ui-switcher>
<web>
<!-- a ui suited for large screens -->
</web>
<mobile>
<!-- a very different ui suited for small mobile screen displays-->
</mobile>
</ui-switcher>
此解决方案可能存在一些缺陷。例如,我们不能在 <mobile> 和 <web> 部分中使用相同的模板引用。 (上面我们使用了#searchInput 和#searchInput2)。
对于这种情况,最佳做法是什么?
【问题讨论】:
标签: angular angular-template ng-template ng-container ng-content