0

I wish to add a class name to NG2 directive in order to apply CSS rules on it. 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 ?

Yuvals
  • 3,094
  • 5
  • 32
  • 60

3 Answers3

2
@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

:host {
  width:100%;
  display:block;
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
  • What is the :host in this case? should I point to a child:host? – Yuvals Oct 25 '16 at 17:39
  • `:host` points to the component itself - the DOM element that hosts the component. From your question it's not clear to me what your problem actually is. If you provide more information, I might be able to provide a better answer. – Günter Zöchbauer Oct 25 '16 at 17:42
0

You declare CSS classes in your stylesheet .. 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. I am not sure if it will target the actual element itself but I think it will.

danday74
  • 52,471
  • 49
  • 232
  • 283
-1

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.

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

</select>

Then create a H1 tag like below.

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

Note. HTML has to be within the div of ng-app you create.

Hope this helps. All the best.