Hi there,
i do have two different css file which needs to use for a component.
a file has been imported in component.css file using @import method
how to change the import css file to different css file by dropdown selection in component.html
example
Component-a.html
dropdown 1-test1.css, 2-test2.css
Component-a.css
@import "../../../../../assets/workflow/css/test1.css";
by default will be test1.css after selected via in dropdown the test1.css will replace with test2.css
Simply to say by overriding the import css.
Hi
I'm glad to hear that you were able to resolve the issue. Your additional advice about the `ngAfterViewInit` and the placement of CSS files in assets are valuable tips that can certainly help others.
If you have any more questions or need further assistance in the future, please don't hesitate to reach out. Thank you for sharing your experience, and I hope your solution is helpful to others as well.
Thanks
Hi,
To programmatically change the CSS file imported in your component's stylesheet based on a dropdown selection, you can use Angular's binding and ngClass directive. Here's a step-by-step guide on how to achieve this:
Create the Component and Handle the Selection:
In your component TypeScript file (Component-a.ts), you need to handle the selection and update the imported CSS file based on the user's choice.
import { Component } from "@angular/core";
@Component({
selector: "app-component-a",
templateUrl: "./component-a.html",
styleUrls: ["./component-a.css"]
})
export class ComponentA {
selectedCss = "test1.css"; // Set the default CSS file
// Handle changes to the dropdown selection
onCssChange() {
// Update the imported CSS file dynamically
const linkElement = document.querySelector("link[rel="stylesheet"]");
if (linkElement) {
linkElement.setAttribute("href", `../../../../../assets/workflow/css/${this.selectedCss}`);
}
}
}
hi Faizal,
Thanks for the feedback.
As i tried it did not changes properly the style loader by importing.
However your solution provides me a hints. i did some modification and now it is works fine
lead to me fix few things and now it is works greatly.
No changes in component style
@Component({
selector: "app-workflow2",
templateUrl: "./workflow2.component.html",
styleUrls: ["./workflow2.component.css"],
encapsulation: ViewEncapsulation.None,
providers: [ConfirmationService, MessageService]
})
theme(styleName: string) {
const head = this.document.getElementsByTagName("head")[0];
let themeLink = this.document.getElementById(
"workflow-theme"
) as HTMLLinkElement;
if (themeLink) {
themeLink.href = `assets/workflow/css/${styleName}.css`;
} else {
const style = this.document.createElement("link");
style.id = "workflow-theme";
style.rel = "stylesheet";
style.type = "text/css";
style.href = `assets/workflow/css/${styleName}.css`;
head.appendChild(style);
}
}
ngAfterViewInit(): void {
this.theme("colourfull");
}