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 ?

6
  • CSS class or ES6 class? Commented Oct 25, 2016 at 15:11
  • CSS, for styling - I need to container (search-form) to have 100% width for example Commented Oct 25, 2016 at 15:11
  • @Yuvals you need to do that in the template where you use it: <search-form class="full-width"></search-form>, for example. Commented Oct 25, 2016 at 15:15
  • Looks like a dup of stackoverflow.com/questions/34641281/… Commented Oct 25, 2016 at 15:20
  • What you tried is CSS that is applied to <search-form> but it is unrelated to "class". Commented Oct 25, 2016 at 15:21

3 Answers 3

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;
}
Sign up to request clarification or add additional context in comments.

2 Comments

What is the :host in this case? should I point to a child:host?
: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.
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.

Comments

-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.

1 Comment

The question is about Angular2. Your answer seems to be about AngularJS.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.