angular - 在组件中使用有条件的不同布局的最佳实践

时间:2018-04-29 19:19:15

标签: angular angular-template ng-template ng-container ng-content

假设我们有几个组件,每个组件应具有不同的布局/ ui(模板),并以显示尺寸为条件。

我的解决方案是创建这样一个组件:

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>部分中使用相同的templateref。 (上面我们使用#searchInput#searchInput2)。


这种情况的 最佳做法 是什么?

1 个答案:

答案 0 :(得分:1)

在您的示例中,如果isSmallfalse,则只需添加CSS类。 您可以通过简单地输入1(而不是2)来解决这个问题,并有条件地添加类。

因此,不是有条件地渲染2个相同的HTML块...而是使用条件CSS类渲染1个块。

以下示例:

@Component({
    selector: 'ui-switcher',
    template: `
        <input class="form-control" [ngClass]="{'mr-2': !isSmall}"> 
        type="text" (keyup)="this.search(searchInput.value)">
`
})

现在,如果您的内容真的更改,并且您需要的不仅仅是简单*ngIf ...那么,一个好的解决方案是使用in tamplate {{ 1}}甚至if...else

参考此处:How to use *ngIf else in Angular?

有关更多条件类使用情况,请查看此帖子:Angular: conditional class with *ngClass

希望它有所帮助! ;)

<强>更新

OP指的是只影响CSS类的更改,但如果您想将组件动态加载到代码块中......我会说你选择了ngComponentOutlet

示例:

if...elseif...else

这种方法的好处在于您可以创建一个地图,并且对于每个选项,您都有 <fieldset *ngFor="let component of components"> <ng-container *ngComponentOutlet="component.name; ngModuleFactory: dynamicComponentsModule;"></ng-container> </fieldset> 与之关联。例如:

Component

我建议这篇帖子提供更多完整的例子:

Dynamic template based on value rather than variable with ngTemplateOutlet

有了这个,在这个答案中,我提供了有关如何获得的信息:

  1. 动态CSS类
  2. 带有模板内map = [ 'option1': ComponentForOption1, 'option2': ComponentForOption2 ];
  3. 的条件HTML
  4. 动态组件加载