简体   繁体   English

Angular 7 - *ngIf 在 div 上使用 class

[英]Angular 7 - *ngIf on div to use class

I have the following div on my angular project:我的 angular 项目中有以下div

<div *ngIf="isPreviewExpanded" class="project-daypart-group-columns-container-expanded pull-left">

Where I have two options: isPreviewExpanded can be true or false我有两个选择: isPreviewExpanded可以是 true 或 false

if it's true I want to show it as it right now but if it's false I need to show like this:如果是真的,我想现在就显示它,但如果它是假的,我需要像这样显示:

<div *ngIf="!isPreviewExpanded" class="project-daypart-group-columns-container-collapsed pull-left">

The class changes within the value of isPreviewExpanded class 在isPreviewExpanded的值内变化

I'm not being able to find any way to do that in the same div , something like:我无法在同一个div中找到任何方法,例如:

<div *ngIf="isPreviewExpanded" class="project-daypart-group-columns-container-expanded; else class='project-daypart-group-columns-container-collapsed'>

Any ideas?有任何想法吗?

Use ngClass directive that adds and removes CSS classes on an HTML element.使用ngClass指令在 HTML 元素上添加和删除 CSS 类。

<div class="pull-left" [ngClass]="'project-daypart-group-columns-container-expanded':isPreviewExpanded, 'project-daypart-group-columns-container-collapsed': !isPreviewExpanded>

You can do it using NgClass .您可以使用NgClass来完成。 There are multiple ways how to do it.有多种方法可以做到这一点。 Some ideas:一些想法:

get dynamicClass(): string {
    return this.isPreviewExpanded ? 
        'project-daypart-group-columns-container-expanded' : 
        'project-daypart-group-columns-container-collapsed';
}

<div *ngIf="isPreviewExpanded class="pull-left' [ngClass]="dynamicClass">

or或者

<div
*ngIf="isPreviewExpanded"
class="pull-left"
[ngClass]="{
    'project-daypart-group-columns-container-expanded': isPreviewExpanded,
    'project-daypart-group-columns-container-collapsed': !isPreviewExpanded
}"
></div>

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM