3

I have a <myComponent ></myComponent> and I want give class to myComponent?

This doesnt worked `<myComponent class="my-class"></myComponent>` 

How can I do that?

2
  • what is the issue you are getting? are you trying to apply style from class within the content of component? Commented Sep 27, 2016 at 14:07
  • Yes @MadhuRanjan, I want give for example border color,width etc. to my control as one control Commented Sep 28, 2016 at 6:44

4 Answers 4

4
class MyComponent {
  @HostBinding('class.my-class')
  isMyClass:boolean = true;
}
Sign up to request clarification or add additional context in comments.

6 Comments

Thank you,and where to use isMyClass property ?
Sorry, I'm not sure I understand the question. isMyClass is just a name I chose. The name doesn't matter. 'class.my-class' defines what class should be added or removed. The value of the property where @HostBinding() is prepended is used to determine if the class should be added or removed (true/false). The only thin where the name of isMyClass is relevent, is when you want to change the value like this.isMyClass = false;
Sorry, I don't know what you mean? What do you try to accomplish? What is not working with the code in your question?
Now it's works,formerly 'my-class' writenn in MyComponent's syleUrl's file. I replace it in styes.css (included in head) ,and everything is ok. I want understand your answer.
The code in my answer just adds my-class to the host element of the MyComponent component. You can now style it from the parent elements styleUrls: ['parent.css'] using :host my-component.my-class { ... } or from MyComponents styleUrls: [my-component.css'] using :host-context(.my-class) { ... }
|
4

Don't think that will work but there are easy workarounds:

If you want to style the placement/color etc of your component:

Best workaround is to place your <myComponent></myComponent> inside a <div> and apply the class to that div

If you want to style the contents of your component:

adding styleUrls in your Component and styling your content with a css file

Comments

1

You can use @Input for your component and set external class in any place.

Example:

<myComponent [styleClass]="'my-class'"></myComponent>>

Your component

/my-component.component.ts

...
@Input() styleClass: string; 
...

/my-component.component.html

   <div [class]="styleClass" ngClass="my-component__container any-other-class">
Component works!
   </div>

Comments

0

you can using host method

import {Component} from "@angular/core";

@Component({
    selector: 'COMPONENT NAME',
    templateUrl: 'COMPONENT URL',
    host: {
        '[class.CLASS NAME]': 'VARIABLE NAME'
    }
})

export class componentName{
}

Comments

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.