Issue with font-size changes using css variables in Angular not updating in browser for specific fields

Utilizing CSS variables, I have implemented a feature that allows users to adjust the font size to small, medium, or large. While this functionality works correctly for most fields, there are certain instances where the value is applied but not displayed.

:host-context(.mediumFont) {
    --fontSize: 11px;
}
:host-context(.largeFont) {
    --fontSize: 12px;
}
:host-context(.smallFont) {
    --fontSize: 10px;
}

refClassArray: RefClassInterface[] = [
        { class: 'font-small', refClass: 'smallFont' },
        { class: 'font-medium', refClass: 'mediumFont' },
        { class: 'font-large', refClass: 'largeFont' },
    ];
defaultFontSize = 'mediumFont';

changeFontSize(selector: string) {
        this.defaultFontSize = selector;
        let docBody = document.body;
        console.log(document.getElementById(selector));
        docBody.classList.add(selector);
        this.refClassArray.forEach((refClass: RefClassInterface) => {
            if (selector !== refClass.refClass) {
                docBody.classList.remove(refClass.refClass);
                document.querySelector('#' + refClass.refClass).setAttribute('style', 'font-weight: normal;' + 'pointer-events: auto;');
            } else {
                document.querySelector('#' + refClass.refClass).setAttribute('style', 'font-weight:' + 'bold;' + 'pointer-events: none;');
            }
        });
        this.ieStyles.iEfont(selector);
    }

The above logic outlines my current approach.

https://i.sstatic.net/Dd0IG.png

https://i.sstatic.net/YCB3P.png

The first image displays an element in which the font-size adjustment is functioning properly. Hovering over the --font-size reveals a value of 11px. In contrast, the second image depicts an element where the font-size adjustment does not yield any visible change when hovering over --font-size. It is worth noting that both elements reside within the <body>.

Answer №1

It is not recommended to directly modify your HTML code as it can leave your application vulnerable to malicious attacks, such as XSS Attacks.

The Angular Team suggests using the Renderer2 instead.

If you decide to update your code to utilize Renderer2, here's what will happen:

refClassArray: RefClassInterface[] = [
        { class: 'font-small', refClass: 'smallFont' },
        { class: 'font-medium', refClass: 'mediumFont' },
        { class: 'font-large', refClass: 'largeFont' },
    ];
defaultFontSize = 'mediumFont';

changeFontSize(selector: string, indexOfClassToAdd: number) {
  this.defaultFontSize = selector;
  const el: Element = document.getElementById(selector));
  // Iterate through each class in the list to remove it.
  this.refClassArray.forEach((refClass: RefClassInterface) => {
    // Remove the class from the specific element only if it is present.            
    if (el.classList.contains(refClass.refClass)) {
      this.renderer2.removeClass(el, refClass.refClass);
    };
  });
  this.renderer2.addClass(el, refClassArray[indexOfClassToAdd].refClass);
};

This means that you need to know which class to apply (and ensure it is defined in the style.scss or appropriate .scss file).

Best regards.

Answer №2

I'm interested to know why you've chosen this method instead of just applying a class with the preferred text size.

Regardless, it seems that your style isn't taking effect due to the lack of specificity in your selector.

To fix this issue, you might consider creating an overly specific selector like this:

body > div * { // styles }

Answer №3

Why not utilize the ngClass directive? Specify three different classes:

.small-font{
    font-size: 10px
}
.medium-font{
    font-size: 11px
}
.large-font{
    font-size: 12px
}

Connect something to the user's selection, such as userChoice: SizeEnum or another variable

Afterward, apply ngClass to your data element for binding

ngClass = "{
 'small-font': userChoice === sizeEnum.small,
 'medium-font': userChoice === sizeEnum.medium,
 'large-font': userChoice === sizeEnum.large
}"

Answer №4

The issue was fixed by relocating the following code:

:host-context(.mediumFont) {
    --fontSize: 11px;
}
:host-context(.largeFont) {
    --fontSize: 12px;
}
:host-context(.smallFont) {
    --fontSize: 10px;
}

It was moved from app.component.scss to styles.scss. This change was necessary because the pop-ups were rendering outside of app.compontnet.html.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Ways to retrieve dropdown values

My HTML code is as follows: <select class="height_selected"> <option>Select Height</option> <option ng-model="userHeight" ng-init="1" value="1">123 cm</option> <option ng-model="userHeight" ng-init="2" v ...

Various hues blending and intertwining with one another

https://i.stack.imgur.com/zLrNK.png Could someone please clarify what is happening here? I'm attempting to change the background color to dodgerblue, but for some reason, the white background color is still showing through. Below is the code snippet ...

Definition file for mapbox-gl-draw in Typescript, also known as d.ts file

I attempted to define the mapbox-gl-draw project in a typed manner but unfortunately, I was unsuccessful. Can anyone provide some guidance on this? Here is how the javascript file looks: 'use strict'; var Setup = require('./src/setup&apos ...

brings fulfillment except for categories

The new satisfies operator in TypeScript 4.9 is incredibly useful for creating narrowly typed values that still align with broader definitions. type WideType = Record<string, number>; const narrowValues = { hello: number, world: number, } sa ...

Issue: The UserComponent is attempting to set the property 'id' of an undefined object, resulting in an error

An error has occurred indicating that the property 'id' cannot be set as it is undefined in the UserComponent file of user.component.ts. Here is the TypeScript code: import { Component, OnInit } from "@angular/core"; import { ActivatedRoute, Rou ...

Using null or undefined for ternary operator formatting in React applications

When styling a component, what should be used if a specific condition is not fulfilled: null, undefined, or something else? For example: errorStyle: { right: locale === Locales.ARABIC ? 0 : null, left: locale !== Locales.ARABIC ? 0 : null, .. ...

Removing HTML DOM elements from a string using JavaScript: A step-by-step guide

Hey there, I'm currently working on my angular application. When it comes to inserting the first 100 characters of content into the "description" meta tag for Facebook sharing, I've run into an issue. The description ends up including the HTML el ...

Exploring Realtime Database Querying with Firebase 5.0

I'm struggling to retrieve all the data from my RTD and store it in an array for iteration. The code below is returning 'undefined'. What could be the issue? export class AppComponent { cuisines$: Observable<any[]>; cuisines: any[ ...

having difficulty transmitting data or interacting with certain buttons on the site using selenium in python

Struggling with reading the HTML of a specific website as I try to perform operations on it. Here's the URL: Encountering 2 issues: Attempted to input a date range, or set it to max for at least 30 years of data. Below is my code snippet trying to s ...

Safari does not stop the scrolling of the <body style="overflow-y: hidden"> tag

Welcome to this simple HTML page <body style="overflow-y: hidden"> ... </body> This page is designed to prevent scrolling by using the CSS property overflow-y: hidden. While this functionality works as intended on most browsers, it does ...

Position the DIVs at the bottom of the TD

I'm having trouble aligning two DIVs within a table TD to the bottom of the table. Despite trying various alignment methods, the left DIV simply won't move. It's crucial for me to design this email responsively, ensuring it still displays co ...

Combining PHP and MySQL with a join statement

I am trying to calculate the average rating for each store in a directory list using MySQL's AVG function. Whenever someone reviews a store, they assign a rating ranging from 1 to 5. This rating is then inserted into the rating column of the reviews ...

Switchable radio options

Currently, I am creating a form containing multiple options that are mutually exclusive. However, none of these options are mandatory. That is why I want to enable the user to uncheck a selected radio button by simply clicking on it again. This way, all th ...

The functionality of Angular animate becomes compromised when there is a conflict between predefined CSS states and transition states

Explore this example CSS code: /* animations at the start */ .error-animation.ng-enter { -webkit-transition: 0.5s linear all; transition: 0.5s linear all; opacity: 0; } ...

Error: The property 'children' is not found in type '{ children?: ReactNode; }'

I have been working on implementing the search bar feature from the provided link. Despite my efforts to match the types correctly, I keep encountering a TypeScript error. Homepage.tsx const [searchQuery, setSearchQuery] = useState(query || '' ...

Retrieving the selected value from a dropdown menu before it is altered using vanilla JavaScript

I am trying to implement a feature where the previous value of a dropdown is captured when it is changed. Essentially, I need to compare the previous and current values of the dropdown and perform an action based on that information. For example, if Option ...

Developing an npm package for storing a communal instance

I am interested in developing an npm library that can be initialized with a specific set of keys and then utilized throughout an entire project. Here is an illustration of how I envision its usage: In the main component or page import customLib from &quo ...

What could be causing the 404 error in my Angular 2 and Node.js setup?

I recently added a form to my website and I'm looking to send the data from the fields to my email address. To handle this task, I've incorporated nodemailer and Node.js into my project. However, when I attempt to submit the form, I encounter a 4 ...

Looking for a way to toggle the visibility of a dropdown list when clicking on an input in Angular7?

My Angular7 application features a dropdown menu that automatically closes when an item is selected. Additionally, I have implemented functionality to toggle the dropdown open and closed by clicking on an input field. You can view a live example of this be ...

Embedding images within written content

Is there a way to insert an image into text from a specific position without using tables? I'm looking for a method other than aligning the image "left or right". https://i.sstatic.net/8gvxk.png ...