我试图将多个(在我的情况下为2)类应用到包含MDBootstrap中的列表项组件的自定义组件:
App.module.ts
<custom-list-component size="w-50">
<custom-list-item-component href="#">list item 1</custom-list-item-component>
<custom-list-item-component href="#">list item 2</custom-list-item-component>
</custom-list-component>
自定义列表,component.component.html
<div [ngClass]="size" class="list-group">
<ng-content></ng-content>
</div>
自定义列表,component.component.ts
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'custom-list-component',
templateUrl: './custom-list-component.component.html',
styleUrls: ['./custom-list-component.component.sass']
})
export class CustomListComponentComponent implements OnInit {
@Input() size: string;
testHorizontal: string = "list-group-horizontal";
constructor() { }
ngOnInit() {
}
}
当我“只”应用自定义列表组件HTML中的大小时,它会将w-50应用于列表,这会使其显示在页面的50%上:
但是现在,我想应用第二个“类”,我想将list-group-horizontal应用于已经应用了w-50的div。我一直在查看文档,我尝试了以下所有解决方案:
<some-element [ngClass]="'first second'">...</some-element>
<some-element [ngClass]="['first', 'second']">...</some-element>
<some-element [ngClass]="{'first': true, 'second': true, 'third': false}">...</some-element>
<some-element [ngClass]="stringExp|arrayExp|objExp">...</some-element>
<some-element [ngClass]="{'class1 class2 class3' : true}">...</some-element>
例如,这不起作用:
<div [ngClass]="'size testHorizontal'" class="list-group">
<ng-content></ng-content>
</div>
因为w-50和list-group-horizontal不应用于div,只有它们的名称。这也适用于上面的其他选项。它看起来像这样:
我如何将属性的内容应用于DIV而不是他们的名字?
提前致谢。
ngClass
指令需要一个字符串作为类附加(在您的情况下)。
所以我们必须用变量创建一个字符串。
[ngClass]="size +' '+ testHorizontal"
用两个变量size +' '+ testHorizontal
构造一个字符串