Modify the innerHTML to adjust font size when a button is clicked in Ionic 5, or eliminate any unnecessary spaces

I have been experimenting with changing the font size of a variable in .html when the variable contains whitespace. In my .ts page, I use the following code to remove the whitespace:

this.contents = this.sanitizer.bypassSecurityTrustHtml(this.product['description']);

When displaying it on the .html page, I use:

<p id="p" class="p" [innerHtml]="contents"></p>

This works well, but I also have a function to change the font size dynamically upon clicking a button. However, everything inside [innerHtml] does not respond to the ChangeFontSize function. Here is an example from the .html page:

<div class="container">
  <div">
  <ion-button (click)="ChangeFontSize('increase')"> A+ </ion-button>
  <ion-button (click)="ChangeFontSize('decrease')"> A- </ion-button>
  </div>

  <h1 id="h"> {{product.title}}</h1>

  <p id="p">{{contents}}</p>

  <p id="p" class="p" [innerHtml]="contents"></p>

  </div>

The h1 element changes dynamically, and the p element with {{contents}} shows whitespace like br> &nbsp, etc. Additionally, using [property]=binding will display extra Safe values.

The issue is that [innerHtml] removes the whitespace but is unable to change the font size. Can anyone suggest possible methods for removing or changing the font-size of [innerHtml]="contents"?

Thank you very much! 🙇🏻‍♂️🙇🏻‍♂️🙇🏻‍♂️

Answer №1

Within the ts component:

  contents = `This initial project includes a basic tabs-based layout designed for applications that will mainly utilize a Tabbed UI.`;

  fontSize = 10;
  constructor(public navCtrl: NavController) {}

  increase() {
    this.fontSize++;
  }

  decrease() {
    this.fontSize--;
  }

In the template section:

 <p [style.font-size.px]="fontSize" class="p" [innerHtml]="contents"></p>
  <button type="button" (click)="increase()">Increase</button>
  <button type="button" (click)="decrease()">Decrease</button>

Explore the Ionic Demo

Answer №2

Hopefully this will be of assistance. It appears that a global class is needed, as shown in the example below.

Example

HTML

<div class="body fontSize16"> // Parent element with font class

<div class="container">
   <ion-button (click)="ChangeFontSize('increase')"> A+ </ion-button>
   <ion-button (click)="ChangeFontSize('decrease')"> A- </ion-button>
</div>

<h1 id="h"> {{product.title}}</h1>

<p id="p">{{contents}}</p>

<p id="p" class="p" [innerHtml]="contents"></p>

TS

import { Renderer2, RendererFactory2 } from '@angular/core';

private fontsizes = [12, 14, 16, 18];
private fontClass = 'fontSize';
private fontIndex = 0;
private renderer: Renderer2;

ngOnInit(): void {
   // Consider setting a default fontsize here.
}

constructor(rendererFactory: RendererFactory2) {
   this.renderer = rendererFactory.createRenderer(null, null);
}

ChangeFontSize(type) {
   // Additional conditions can be added for array length or default value
   if (type === 'increase') {
     this.fontIndex + 1;
   } else if (type == 'decrease') {
     // More conditions should be added to check the index of the array
     this.fontIndex - 1;
   }
   this.removeClass(this.fontClass + this.fontsizes[this.fontIndex ]);
   this.addClass(this.fontClass + this.fontsizes[index]);
   this.fontIndex = index;
}

addClass(className: string) {
   this.renderer.addClass(document.body, className);
}

removeClass(className: string) {
   this.renderer.removeClass(document.body, className);
}

CSS

body.fontSize16 .p{
   font-size: 16px;
}

SASS

body {
     &.fontSize16 {
        .p{ 
          font-size: 16px;
        }
     }
   }

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

Issue: Database not updating after input via AJAXExplanation: Despite submitting new data through AJAX, the

I've been struggling to display the UPDATED database on my initial html page after submitting new information. Despite successfully updating the database using AJAX, I can only see the outdated version. Any assistance in resolving this issue would be ...

Discover exclusive outcomes within the Dropdown selection

I'm populating a select dropdown dynamically from a JSON array of objects and would like to filter by tag. The issue I'm facing is that I am getting duplicate tags because multiple results can have the same tag. How can I ensure that only unique ...

Exploring HTML5 using QXmlQuery

Looking to execute XQueries on a batch of HTML5 documents using QT (currently at 5.8...) HTML/HTML5 documents, unlike XHTML/XHTML5, are not well-formed XML files. HTML introduces elements that XML parsers cannot handle off the bat (such as special characte ...

Switching over from an external style sheet to inline elements can be tricky, especially when it comes to integrating "dropdown" styles properly

I successfully created a stylish menu using a specific style sheet, but now I'm facing issues when trying to incorporate this menu into web pages with different style requirements. Realizing that loading the style sheet onto these new pages wreaks hav ...

The quirks of JSON.stringify's behavior

I am in the process of gathering values to send back to an ASP.NET MVC controller action. Despite using JSON.stringify, I keep encountering Invalid JSON primitive exceptions and I am unsure why. I have a search value container named searchValues. When I i ...

Concurrent Openlayers maps in Rails - A Viable Option

I've been playing around with Openlayers maps on my website. The map functionality is working perfectly, but I'm having trouble getting the maps to display correctly on my page. My goal is to show a map in each search result on my screen - one m ...

Sharing JavaScript code between Maven modules can be achieved by following these steps

My Maven project has a unique structure that includes: "Base" module -- containing shared Java files -- should also include shared JavaScript files Module 1 -- using shared Java files as a Maven dependency -- should utilize shared JavaScript files throug ...

``There seems to be a malfunction with the modal feature in the asp.net

Within my strongly typed view, I have a loop that iterates over a list of objects fetched from a database. Each object is displayed within a jumbotron element, accompanied by a button labeled "Had role before". When this button is clicked, a modal opens wh ...

Unique column arrangement specifically designed for the initial row within the loop

My webpage features a layout that showcases 4 images on each row. However, I am looking to create a special first row with a unique column configuration compared to the rest of the rows. Here is an example of what I have in mind: This particular row will ...

What is the process for refreshing one observable with data from another observable?

As a complete beginner to these technologies, please bear with me if my question sounds strange and the terminology is not quite right. I have a component that displays data in a table format. export class SourceFieldComponent implements OnInit { ... ...

How can JQuery be used to implement "scrolling" buttons and automatically update the main page with fresh data?

I am attempting to achieve the following: 1 - Use jQuery to update index.html with the content from output.html (only update when there are differences in data, and ideally only update the parts that have changed). 2 - Add two buttons in the header ...

The situation where a Javascript switch case continues to fall through to the default case even when a 'break' statement

I am currently setting up a node.js discord bot that utilizes firebase to save a user's status. My switch statement is functioning smoothly, handling each command effectively. The default case looks like this: default: message.reply("Unknown comm ...

Unable to load module/controller file from Angular 1 into view/html

var app = angular.module("appModule",[]); app.controller("viewController",function($scope){ $scope.greeting = "Welcome to the future"; }); <html> <head> <script src="Scripts/script.js"></script> <script ...

Compile the sources of an npm dependency using Brunch

Recently, I've been facing an issue while trying to develop my web application using Brunch. The problem arises from a specific npm package called animated-vue, which consists of sources programmed in ES2016. After adding this package as a dependency ...

Tips for extracting a substring from a Django variable [HTML]

I am struggling to properly format an img element with a src attribute. The URL example I am working with is , where the number 45 represents the first two characters of the full item.image attribute. My trouble lies in extracting the {{item.image[0,2]}} ...

Angular-fontawesome icons are experiencing issues with their background color not scaling properly

Currently utilizing angular-fontawesome, I am seeking to alter the background color of a font-awesome fa-icon <fa-icon class="vue-icon" [icon]="faVue" ></fa-icon> To change the color, I modified the CSS using ...

What steps can I take to ensure that my email signature is optimized for mobile devices and responsive

I need assistance with formatting my email signature, which currently includes a simple table with a logo in one column and contact details in the other. I want to modify it to be responsive so that on smaller devices, the logo appears above the contact d ...

Tips for making inline elements match the line height

Consider this block element : <div style="background-color: gray; line-height: 30px;"> Some text and a <a style="background-color: yellow;">link<\a> <\div> Why is it that the yellow color does not extend the full hei ...

Error Encountered: Unhandled Runtime Error in Next.js with Firebase - TypeError: Unable to access the property 'initializeApp' as it is undefined

It's baffling why this error keeps appearing... my suspicion is directed towards this particular file. Specifically, firebaseAuth={getAuth(app)} might be the culprit. Preceding that, const app = initializeApp(firebaseConfig); is declared in "../f ...

Looking for Protractor CSS functionalities nodes

I tried the code below but am having trouble locating the "Login" text using Protractor: <div _ngcontent-c2="" class="align-center"> <img _ngcontent-c2="" alt="Autoprax" class="ap-logo" src="/images/apLogoSmall.svg" style="width: 100%"> ...