【问题标题】:angular - best practice for using conditionally different layouts in a component角度 - 在组件中使用有条件不同布局的最佳实践
【发布时间】: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>

此解决方案可能存在一些缺陷。例如,我们不能在 &lt;mobile&gt;&lt;web&gt; 部分中使用相同的模板引用。 (上面我们使用了#searchInput#searchInput2)。


对于这种情况,最佳做法是什么?

【问题讨论】:

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


    【解决方案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 if...else 甚至 @987654330 @。

    参考这里:How to use *ngIf else in Angular?

    更多条件类的用法,查看这篇文章:Angular: conditional class with *ngClass

    希望对您有所帮助! ;)

    更新:

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

    例子:

            <fieldset *ngFor="let component of components">
                <ng-container *ngComponentOutlet="component.name;
                                    ngModuleFactory: dynamicComponentsModule;"></ng-container>
            </fieldset>
    

    这种方法的好处是您可以创建一个地图,并且对于每个选项,您都有一个与之关联的Component。示例:

    map = [
       'option1': ComponentForOption1,
       'option2': ComponentForOption2
    ];
    

    我建议这篇文章提供更完整的示例:

    Dynamic template based on value rather than variable with ngTemplateOutlet

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

    1. 动态 CSS 类
    2. 带有模板内的条件 HTML if...elseif...else
    3. 动态组件加载

    【讨论】:

    • 不,更改不仅仅是一个 css 类。假设我们有许多布局更改,在所有组件中考虑它是很麻烦的。我们喜欢在单个组件中处理它。
    • @Fartab 嘿!我已经更新了我的答案,并解释了如何动态加载组件。如果有不清楚的地方,请告诉我。干杯! :D
    猜你喜欢
    • 1970-01-01
    • 2023-01-18
    • 1970-01-01
    • 2017-04-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多