简体   繁体   English

如何将类名称添加到Angular2指令

[英]How to add Class name to Angular2 directive

I wish to add a class name to NG2 directive in order to apply CSS rules on it. 我希望在NG2指令中添加一个类名,以便对其应用CSS规则。 Given the following component: 给定以下组件:

@Component({
  moduleId: module.id,
  selector: 'search-form',
  templateUrl: 'search-form.component.html',
  styleUrls: [ 'search-form.component.css']
})

I tried this: 我尝试了这个:

search-form {
  width:100%;
  display:block;
}

But it did not work. 但这没有用。

How can I add a class to search-form ? 如何向search-form添加类?

@Component({ // or @Directive({
  // use `host:` or `@HostBinding()` (not both)
  // host: {'[class.someclass]': 'true'}
})
class SearchFormComponent {
  @HostBinding('class.someclass')
  someClass = true;
}

Perhaps you mean adding styles to "self" by adding this CSS to search-form.component.css 也许您的意思是通过将此CSS添加到search-form.component.css来为“ self”添加样式

:host {
  width:100%;
  display:block;
}

You declare CSS classes in your stylesheet .. search-form.component.css 您在样式表中声明CSS类.. search-form.component.css

If you want to target the component in your stylesheet then you could do ... 如果要在样式表中定位组件,则可以...

search-form {
  width:100%;
  display:block;
}

This will target elements with the tag search-form. 这将使用标签搜索表单来定位元素。

Because Angular2 is component based, it only targets elements inside the component. 由于Angular2基于组件,因此它仅针对组件内部的元素。 I am not sure if it will target the actual element itself but I think it will. 我不确定它是否会针对实际元素本身,但我认为会。

I can show an example of this. 我可以举一个例子。

Firstly create a stylesheet. 首先创建一个样式表。 like 喜欢

<style>
.red
{
color:red;
}
.blue
{
color:blue;
}
</style>

Then in your HTML include your style sheet along with angular.min.js and create a dropdown as below. 然后在您的HTML中包括您的样式表以及angular.min.js并创建一个如下所示的下拉列表。

<select ng-model="a">
<option value="red">red</option>
<option value="blue">blue</option>

</select>

Then create a H1 tag like below. 然后创建一个H1标签,如下所示。

<h1 ng-class="a">Header color</h1>

Note. 注意。 HTML has to be within the div of ng-app you create. HTML必须在您创建的ng-app的div内。

Hope this helps. 希望这可以帮助。 All the best. 祝一切顺利。

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

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