2

When creating an angular component, how can make the css file conditional. ie., say for example, if I want style1.css when the user.type = 'A' and style2.css when user.type='B'. Is this possible?

2

1 Answer 1

0

You can do it with code that is like this:

main index.html

<head>
   <link id="theme" rel="stylesheet" href="firstsheet.css">
</head>

Then your component code would look like this

@Component({
   ........
})
export class MyComponent {
    constructor (@Inject(DOCUMENT) private document) { }

    switchTheme() {
      this.document.getElementById('theme').setAttribute('href', 'secondsheet.css');
    }
}
Sign up to request clarification or add additional context in comments.

2 Comments

Will this affect the whole DOM? or just the component's style? I was looking at something like. @Component({ selector: 'app-items-list', templateUrl: './items-list.component.html', styleUrls: [ if (something) :'./items-list.component.css'?'./items-list.component2.css' ] })
No, this solution only works for the whole DOM. Because of the way view encapsulation works at the component level, the CSS classes get renamed arbitrarily (to enable encapsulation) so there is no way to replace them programmatically

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.