How to dynamically load CSS with Angular - css

For the last couple of days I've been trying several answers, suggestions and tutorials for the problem, but unfortunately non of them did the trick.
The closest one was this:
https://juristr.com/blog/2019/08/dynamically-load-css-angular-cli/
But it uses "extractCss" which has been deprecated since the article has been published.
According to the article:
"styles.js" file should disappear in the Inspector > Network > JS
Clicking the button should add its css file in Inspector > Network > CSS
But neither of these two is happening at the moment.
app.component.ts
const head = this.document.getElementsByTagName('head')[0];
console.log(head);
let themeLink = this.document.getElementById(
'client-theme'
) as HTMLLinkElement;
if (themeLink) {
themeLink.href = styleName;
} else {
const style = this.document.createElement('link');
style.id = 'client-theme';
style.href = `${styleName}`;
head.appendChild(style);
}
}
app.component.html
<head>
</head>
<body>
<button type="button" (click)="loadStyle('client-a-style.css')">STYLE 1</button>
<button type="button" (click)="loadStyle('client-b-style.css')">STYLE 2</button>
</body>
</html>
angular.json
"styles": [
"src/styles.css",
{
"input": "src/client-a-style.css",
"bundleName": "client-a",
"inject": false
},
{
"input": "src/client-b-style.css",
"bundleName": "client-b",
"inject": false
}
These are the main parts of my code.
Hopefully I've explained the problem sufficiently.
Thank you for helping!

You can put your additionals .css in the folder assets (and remove from angular.json)
Then the only change is add the "assets" folder to the href
loadStyle(styleName: string) {
const head = this.document.getElementsByTagName('head')[0];
let themeLink = this.document.getElementById(
'client-theme'
) as HTMLLinkElement;
if (themeLink) {
themeLink.href = `assets/${styleName}`; //<--add assets
} else {
const style = this.document.createElement('link');
style.id = 'client-theme';
style.rel = 'stylesheet';
style.type = 'text/css';
style.href = `assets/${styleName}`; //<--add assets
head.appendChild(style);
}
}
a stackblitz

I think you are missing a property in the link tag, add this to the place you create the link element and it should work.
style.rel = 'stylesheet';

One of possible solution to this task:
import { DOCUMENT } from '#angular/common';
import { Inject, OnDestroy, OnInit, Renderer2 } from '#angular/core';
export class MyComponent implements OnInit, OnDestroy {
private style?: HTMLLinkElement;
constructor(
#Inject(DOCUMENT) private document: Document,
private renderer2: Renderer2,
) {}
public ngOnInit(): void {
const cssPath = '/link/to/style.css';
// Create a link element via Angular's renderer to avoid SSR troubles
this.style = this.renderer2.createElement('link') as HTMLLinkElement;
// Add the style to the head section
this.renderer2.appendChild(this.document.head, this.style);
// Set type of the link item and path to the css file
this.renderer2.setProperty(this.style, 'rel', 'stylesheet');
this.renderer2.setProperty(this.style, 'href', cssPath);
}
public ngOnDestroy(): void {
// Don't forget to remove style after component destroying
this.renderer2.removeChild(this.document.head, this.style);
}
}
If and if your css-files are on the server, so you probably should update your proxy.conf.json file to have access this file from localhost while serve mode is on.

Related

usage of ref in vue3

I wrote a vue3 component which uses the VirtualScroller from PrimeVue and I would like to scroll to the end of the scroller each time I'm adding new elements. For that, there is scrollInView method which is defined on the component and documented here
My code looks like this (it's typescript with vue-class-component and single file syntax):
<template>
...
<VirtualScroller :items="content" :itemSize="50" class="streamscroller" ref="streamscroller">
<template v-slot:item="{ item }">
<pre>{{ item }}</pre>
</template>
</VirtualScroller>
...
</template>
<script lang="ts">
...
import { ref, ComponentPublicInstance } from "vue";
import VirtualScroller from "primevue/virtualscroller";
...
#Options({
components: {
VirtualScroller,
...
},
})
export default class StreamResultViewer extends Vue {
streamscroller = ref<ComponentPublicInstance<VirtualScroller>>();
content: string [] = [ "No output" ];
...
mounted(): void {
...
console.debug("scroller mounted: ", this.streamscroller.value); // <=== here, already the value is indefined
}
onData(msg: string): void {
const lines = msg.split('\n');
const content = [...this.content, ...lines];
this.content = content;
console.debug("scroller: ", this.streamscroller.value); // <== always undefined
this.streamscroller.value?.scrollInView(this.content.length, 'to-end', 'smooth'); // <== so never called
}
...
The virtual scroller works well (I can add lines each time they arrives and the scroll bar moves...) but I can never call the scroll method because the ref is undefined...
I'd be very grateful for any clue...
Thank you
The only workaround I found is too use $refs like this:
onData(msg: string): void {
const lines = msg.split('\n');
const content = [...this.content, ...lines];
this.content = content;
const scroller = this.$refs.streamscroller as VirtualScroller;
scroller.scrollInView(this.content.length, 'to-end', 'smooth');
}
This way, I am able to call the scrolling method and it works fine.
If someone can explain how it should work normally with ref<T>() in the vue-class-component + typescript mode, I'd be glad to hear that.

Apply different css files between 2 sub roots

I have an angular app, which consists of a website and system.
so I have made 2 sub roots under app root, websiteMaster, and systemMaster.
CSS files of the website don't have to be loaded when I'm logged in.
CSS files of the systems don't have to be loaded when I'm logged out.
so I need to load CSS files in websiteMaster only for website sub root components and to load CSS files in systemMaster only for system sub root components.
Is there a way to apply that using Angular 8?
Thanks in advance
You've to manually load/unload css files in a main/root(whatever you want to call it) component in one of your subroot module.
Let suppose websiteMaster module has following structure
Routes:
// Wrapping all routes in a parent component
const routes: Routes = [
{ path: '', component: WebsiteMasterRootComponent, children: [
{ path: 'any-path', component: AnyComponent },
{ path: 'any-other-path', component: AnyOtherComponent },
]
}];
WebsiteMasterRootComponent: which will load and unload css files related to this module
export class WebsiteMasterRootComponent implements OnInit, OnDestroy {
// css files required for current module
private styles = [
{ id: 'css-file-1', path: 'assets/css/css-file-1.css' },
{ id: 'css-file-2', path: 'assets/css/css-file-2.css' },
{ id: 'css-file-3', path: 'assets/css/css-file-3.css' },
];
constructor() {}
ngOnInit() {
this.styles.forEach(style => this.loadCss(style));
}
ngOnDestroy() {
// remove css files from DOM when component is getting destroying
this.styles.forEach(style => {
let element = document.getElementById(style.id);
element.parentNode.removeChild(element);
});
}
// append css file to DOM dynamically when current module is loaded
private loadCss(style: any) {
let head = document.getElementsByTagName('head')[0];
let link = document.createElement('link');
link.id = style.id;
link.rel = 'stylesheet';
link.type = 'text/css';
link.href = style.path;
head.appendChild(link);
}}

Angular Material Dialog panelClass Wont Update

I'm working with an Angular Material Dialog Box and I'm trying to make the background a custom color.
This question has been asked quite a few times and I've tried to apply the answer but it doesn't seem to work. Specifically, it doesn't appear that the panelClass of the dialog container is updating. Below is the component opening the dialog, the _theming.scss file, and the HTML element
import { Component, OnInit} from '#angular/core';
import { AuthService } from 'src/app/AuthenticationPackage/core/auth.service'
import { MatDialog, MatDialogConfig } from '#angular/material';
import { FactiondialogComponent } from './factiondialog/factiondialog.component';
#Component({
selector: 'app-factions2',
templateUrl: './factions2.component.html',
styleUrls: ['./factions2.component.scss']
})
export class Factions2Component implements OnInit {
constructor( public authService: AuthService,
public dialog: MatDialog ) { }
ngOnInit(){ }
openDialog(faction): void{
const dialogConfig = new MatDialogConfig()
dialogConfig.disableClose = true;
dialogConfig.autoFocus = true;
dialogConfig.data = {faction};
dialogConfig.panelClass = ".faction-dialog";
const dialogRef = this.dialog.open(FactiondialogComponent, dialogConfig)
dialogRef.afterClosed().subscribe(result => {
console.log("dialog closed");
});
}
}
The _theming.scss section:
#mixin mat-dialog-theme($theme) {
$background: map-get($theme, background);
$foreground: map-get($theme, foreground);
.faction-dialog{
background-color:rgb(28, 31, 32)
}
.mat-dialog-container {
#include _mat-theme-elevation(24, $theme);
background: mat-color($background, dialog);
color: mat-color($foreground, text);
}
}
#mixin mat-dialog-typography($config) {
.mat-dialog-title {
#include mat-typography-level-to-styles($config, title);
}
}
This is the markup generated and but it does not include my custom class.
<mat-dialog-container aria-modal="true" class="mat-dialog-container ng-tns-c12-2 ng-trigger ng-trigger-dialogContainer ng-star-inserted" tabindex="-1" id="mat-dialog-0" role="dialog" style="transform: none;"><!--bindings={
"ng-reflect-portal": ""
}--><app-factiondialog _nghost-lda-c13="" class="ng-star-inserted"><div _ngcontent-lda-c13="" class="dialogCard"><h2 _ngcontent-lda-c13="" class="mat-dialog-title">The Harpers</h2><mat-dialog-content _ngcontent-lda-c13="" class="mat-typography mat-dialog-content"><p _ngcontent-lda-c13="">
SOME CONTENT THAT DOESNT MATTER TO THE EXAMPLE
</p></mat-dialog-content><mat-dialog-actions _ngcontent-lda-c13="" align="end" class="mat-dialog-actions"><button _ngcontent-lda-c13="" mat-button="" mat-dialog-close="" class="mat-button mat-button-base" ng-reflect-dialog-result="" type="button"><span class="mat-button-wrapper">Close</span><div class="mat-button-ripple mat-ripple" matripple="" ng-reflect-centered="false" ng-reflect-disabled="false" ng-reflect-trigger="[object HTMLButtonElement]"></div><div class="mat-button-focus-overlay"></div></button></mat-dialog-actions></div></app-factiondialog></mat-dialog-container>
I believe the upper section should say:
<mat-dialog-container aria-modal="true" class="mat-dialog-container faction-dialog ng-tns-c12-2 ng-trigger ng-trigger-dialogContainer ng-star-inserted" tabindex="-1" id="mat-dialog-0" role="dialog" style="transform: none;">
but I'm not sure since I haven't gotten this to work. I've followed the documentation:
https://material.angular.io/components/dialog/api#MatDialogConfig
I'm not sure if there's something I need to add in my app module or somewhere else.
Per the request of Mr. Khan:
faction2.component.ts:
openDialog(faction): void{
const dialogRef = this.dialog.open(FactiondialogComponent, {panelClass: 'faction-dialog'})
dialogRef.afterClosed().subscribe(result => {
console.log("dialog closed");
});
}
Screen with modal open:
HTML Inspect Element
<mat-dialog-container aria-modal="true" class="mat-dialog-container ng-tns-c12-4 ng-trigger ng-trigger-dialogContainer ng-star-inserted" tabindex="-1" id="mat-dialog-2" role="dialog" style="transform: none;"><!--bindings={
"ng-reflect-portal": ""
}--><app-factiondialog _nghost-yis-c13="" class="ng-star-inserted"><div _ngcontent-yis-c13="" class="dialogCard"><h2 _ngcontent-yis-c13="" class="mat-dialog-title"></h2><mat-dialog-content _ngcontent-yis-c13="" class="mat-typography mat-dialog-content"><p _ngcontent-yis-c13=""></p></mat-dialog-content><mat-dialog-actions _ngcontent-yis-c13="" align="end" class="mat-dialog-actions"><button _ngcontent-yis-c13="" mat-button="" mat-dialog-close="" class="mat-button mat-button-base" ng-reflect-dialog-result=""><span class="mat-button-wrapper">Close</span><div class="mat-button-ripple mat-ripple" matripple=""></div><div class="mat-button-focus-overlay"></div></button></mat-dialog-actions></div></app-factiondialog></mat-dialog-container>
If you want to add your own custom class to style the material modal, then firstly passes your custom class to the panelClass key in your modal this way:
this.dialogRef = this.dialog.open(AddCustomComponent,{
panelClass: 'custom-dialog-container', //======> pass your class name
});
this.dialogRef.afterClosed();
Once that's done, all you gotta do is style your modal by using your class and other models won't be affected. For example, you can remove the padding and margin this way.
/*Material Dialog Custom Css*/
.custom-dialog-container .mat-dialog-container{
padding: 0;
}
.custom-dialog-container .mat-dialog-container .mat-dialog-content{
margin: 0;
}
/*---------------------------*/
The panelClass gets added to the parent of the dialog container, so the space is what I was missing:
.custom-dialog-container <<space>> .mat-dialog-container{
padding: 0;
}
Also use ng-deep or put the style in the root stylesheet, not the component
Great answer above, but I wanted to just extend it by saying that the MatDialogConfig can also be passed via some config object.
i.e. I passed in custom class SingleViewDialog for my scenario, where the my-custom-maximize padding override was added to our mat-dialog.scss override file:
export interface SingleViewDialog {
examUID: string;
examData: TrendOctExam;
layoutMode: Layout;
}
public launchSingleView(examUID: string, examData: TrendOctExam) {
const config: MatDialogConfig<SingleViewDialog> = {};
config.hasBackdrop = true;
config.disableClose = false;
config.panelClass = 'my-custom-maximize';
const mode: Layout = 'volume2d';
config.data = { examUID, examData, layoutMode: mode};
const dialogRef = this.matDialog.open(OCTThreeDSingleComponent, config ); //*** INJECT HERE ***
dialogRef.afterClosed().subscribe(_ => this.viewStateService.updateLayoutMode('glaucoma'));
}

Aurelia: Stylesheet loaded but not removed

In an aurelia project I have several components that import additional stylesheets, e.g. from semantic-ui. After leaving the components page, the stylesheet is still active and not removed. Is it possible to 'unload' the stylesheets?
Update (2018-03-27):
I submitted a PR to enable this as an opt-in, you can keep track of it here: https://github.com/aurelia/templating-resources/pull/344
Original answer:
A word of warning, this is untested and aurelia-internals-hacky.
What you could do is override the default CSSViewEngineHooks and CSSResource classes to keep track of the style elements it injects, and then add an beforeUnbind hook to remove the styles again.. before unbind (right after detached)
Unfortunately the CSSResource class is not exported from aurelia-templating-resources so we need to go one layer deeper and overwrite the existing style loader plugins that returns instances of CSSResource.
Here's how:
First we grab the code from aurelia-templating-resources/src/css-resource.js, put it in our own src/css-resource.js/ts and make a few tweaks to it (don't think too much of the size, it's just a copy-paste with a few small tweaks, annotated with comments):
import {ViewResources, resource, ViewCompileInstruction} from 'aurelia-templating';
import {Loader} from 'aurelia-loader';
import {Container} from 'aurelia-dependency-injection';
import {relativeToFile} from 'aurelia-path';
import {DOM, FEATURE} from 'aurelia-pal';
let cssUrlMatcher = /url\((?!['"]data)([^)]+)\)/gi;
function fixupCSSUrls(address, css) {
if (typeof css !== 'string') {
throw new Error(`Failed loading required CSS file: ${address}`);
}
return css.replace(cssUrlMatcher, (match, p1) => {
let quote = p1.charAt(0);
if (quote === '\'' || quote === '"') {
p1 = p1.substr(1, p1.length - 2);
}
return 'url(\'' + relativeToFile(p1, address) + '\')';
});
}
class CSSResource {
constructor(address: string) {
this.address = address;
this._scoped = null;
this._global = false;
this._alreadyGloballyInjected = false;
}
initialize(container: Container, target: Function): void {
this._scoped = new target(this);
}
register(registry: ViewResources, name?: string): void {
if (name === 'scoped') {
registry.registerViewEngineHooks(this._scoped);
} else {
this._global = true;
}
}
load(container: Container): Promise<CSSResource> {
return container.get(Loader)
.loadText(this.address)
.catch(err => null)
.then(text => {
text = fixupCSSUrls(this.address, text);
this._scoped.css = text;
if (this._global) {
this._alreadyGloballyInjected = true;
// DOM.injectStyles(text); <- replace this
// this is one of the two possible moments where the style is injected
// _scoped is the CSSViewEngineHooks instance, and we handle the removal there
this._scoped.styleNode = DOM.injectStyles(text);
}
});
}
}
class CSSViewEngineHooks {
constructor(owner: CSSResource) {
this.owner = owner;
this.css = null;
}
beforeCompile(content: DocumentFragment, resources: ViewResources, instruction: ViewCompileInstruction): void {
if (instruction.targetShadowDOM) {
DOM.injectStyles(this.css, content, true);
} else if (FEATURE.scopedCSS) {
let styleNode = DOM.injectStyles(this.css, content, true);
styleNode.setAttribute('scoped', 'scoped');
} else if (this._global && !this.owner._alreadyGloballyInjected) {
// DOM.injectStyles(this.css); <- replace this
// save a reference to the node so we can easily remove it later
this.styleNode = DOM.injectStyles(this.css);
this.owner._alreadyGloballyInjected = true;
}
}
// this is the hook we add, here we remove the node again
beforeUnbind(): void {
if (this._global && this.owner._alreadyGloballyInjected) {
DOM.removeNode(this.styleNode);
this.owner._alreadyGloballyInjected = false;
}
}
}
export function _createCSSResource(address: string): Function {
#resource(new CSSResource(address))
class ViewCSS extends CSSViewEngineHooks {}
return ViewCSS;
}
Then, in our main.ts/js we do the same thing aurelia-templating-resources.js does, but with our own version.
So we do this after the call to aurelia.use.standardConfiguration() etc, to override the existing one
let viewEngine = config.container.get(ViewEngine);
let styleResourcePlugin = {
fetch(address) {
return { [address]: _createCSSResource(address) };
}
};
['.css', '.less', '.sass', '.scss', '.styl'].forEach(ext => viewEngine.addResourcePlugin(ext, styleResourcePlugin));
And that should pretty much do the trick.. :)
I have found a plugin to resolve the issue:
https://github.com/jbockle/aurelia-useable-style-loader
But for the latest Webpack webpack.config.js should be a little bit different than in a plugin readme.
You should load .css files this way:
use: [
{ loader: 'style-loader', options: { injectType: 'lazyStyleTag' } },
'css-loader'
]
Instead of this:
use: ['style-loader/useable', 'css-loader']

How to have sub components CSS class react on parent components CSS class?

I am trying to get my head around a scenario with CSS components:
I have a react component that uses its own classes. This component has a little helper subcomponent that also has its own classes. Now: When a specific state in the main component is set and a specific class is applied then the helper component's css should react on that class.
For instance:
Component A uses Component B to show something.
Component A gets clicked on and react sets a "clicked"-class on that component
Component B should then visually react on that class
In plain CSS (or similar) I would do this:
Component A:
.component {
height: 10px;
}
.component.clicked {
height: 5px;
}
Component B
.clicked {
.subComponent {
background-color: orange;
}
}
I know that there is a react way to do this. This kind of thing should be done with states and props which are being passed between the components so that this kind of situation gets avoided altogether. But I am currently refacturing a project that still has these issues and I don't really get how to do this properly with react-css-modules.
By the way: My current workaround uses :global but I'd really, really like to avoid this...
Component B:
.clicked:onclick, .subComponent {
// code ...
}
This should do it.
If not I'm just bad at css, or confused about your question.
Parent:
var ComponentA = React.createClass({
getInitialState: function() {
return {
isClicked: false
}
},
onClick: function() {
this.setState({ isClicked: !this.state.isClicked });
}),
render() {
return (
<div className={this.state.isClicked ? "component clicked" : "component"}>
<ComponentB isClicked={this.state.isClicked}/>
</div>
);
}
});
Child:
var ComponentB = React.createClass({
getDefaultProps: function() {
return {
isClicked: false
}
},
render() {
return (
<div className={this.props.isClicked ? "subComponent clicked" : "subComponent"}>
I am the subComponent
</div>
);
}
});

Resources