如何在主机元素中添加“class”?

问题描述 投票:140回答:3

我不知道如何添加到我的组件<component></component>动态类属性,但在模板html(component.html)内。

我找到的唯一解决方案是通过“ElementRef”原生元素修改项目。做一些非常简单的事情似乎有点复杂。

另一个问题是必须在组件范围之外定义CSS,从而破坏组件封装。

有更简单的解决方案吗?像模板中的<root [class]="..."> .... </ root>之类的东西。

angular angular2-template
3个回答
251
投票
@Component({
   selector: 'body',
   template: 'app-element',
   // prefer decorators (see below)
   // host:     {'[class.someClass]':'someField'}
})
export class App implements OnInit {
  constructor(private cdRef:ChangeDetectorRef) {}

  someField: boolean = false;
  // alternatively also the host parameter in the @Component()` decorator can be used
  @HostBinding('class.someClass') someField: boolean = false;

  ngOnInit() {
    this.someField = true; // set class `someClass` on `<body>`
    //this.cdRef.detectChanges(); 
  }
}

Plunker example

这样您就不需要在组件外部添加CSS。 CSS喜欢

:host(.someClass) {
  background-color: red;
}

从组件内部开始工作,只有在主机元素上设置类someClass时才应用选择器。


145
投票

Günter的答案很棒(问题是要求动态类属性)但我认为我只是为了完整而添加...

如果您正在寻找一种快速而简洁的方法来将一个或多个静态类添加到组件的主机元素(即,出于主题样式目的),您可以这样做:

@Component({
   selector: 'my-component',
   template: 'app-element',
   host: {'class': 'someClass1'}
})
export class App implements OnInit {
...
}

如果你在entry标签上使用一个类,Angular将合并这些类,即

<my-component class="someClass2">
  I have both someClass1 & someClass2 applied to me
</my-component>

1
投票

我是这样做的(Angular 7):

在组件中,添加一个输入:

@Input() componentClass: string = '';

然后在组件的HTML模板中添加如下内容:

<div [ngClass]="componentClass">...</div>

最后在实例组件的HTML模板中:

<root componentClass="someclass someotherclass">...</root>

免责声明:我对Angular很新,所以我可能会在这里幸运!

© www.soinside.com 2019 - 2024. All rights reserved.