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

Tips on creating a "CSS3 blink animation" using the visibility attribute

I'm attempting to create an old-school blink effect on some DIVs. They should start off as invisible and then quickly become visible for a moment, repeating this sequence in an infinite loop. According to CSS specifications, the "visible" property is ...

Loading a different webpage seamlessly without having to reload the current one

Here is a snippet of my code in okay.html: {% extends "sch/base.html" %} {% load staticfiles %} {% block content %} <div class="row" id="ada"> <form action="" method="post> {% csrf_token %} <div align="center" class="cont ...

What are the main differences between Fluid Layout and Grid?

It seems like there's some vital information I haven't come across yet. Are fluid layouts and grid layouts interchangeable? I keep hearing about this baseline concept, but I can't quite grasp its purpose. Does it serve as a guide for alignin ...

Transition from traditional class-based components to functional components

I am utilizing the ref from the parent class to access the child class. However, in this scenario, I want to access the child functional component from the parent class. In the parent class: class Waveform extends Component { constructor(props){ s ...

Create a self-bot that can generate a new server

I am currently working on a discord.js self-bot and I need assistance in creating a server. Any guidance would be greatly appreciated. I have experimented with the client.user method, but did not achieve the desired result. If it is not possible to c ...

Eliminate repeated elements in a selection using an AngularJS custom directive

I am in the process of creating an events app that utilizes JSON data from Drupal to showcase events using AngularJS within a Drupal module. One of the keys in the JSON object is 'genre', which I'm utilizing in a select dropdown to allow use ...

Mobile media queries are ineffective despite implementing the viewport meta tag

I am facing an issue that even though I have tried various solutions, my media queries are not working on mobile devices after adding the viewport meta tag. Can anyone provide insight into why this might be happening? Update: Upon further investigation, I ...

I'm only appending the final element to the JavaScript array

Currently, I have the following code: I'm endeavoring to create a new JSON object named dataJSON by utilizing properties from the GAJSON object. However, my issue arises when attempting to iterate over the GAJSOn object; only its last element is added ...

Is it possible in HTML to detect *any* changes made to an input, not just those made by the keyboard?

Let's consider a scenario where we have an input element like this: <input id="myInput" type="text" /> The question now arises, how can we detect when the value of this input is changed programmatically (such as through $("#myInput").val("new ...

Tips for maximizing responsiveness with display:flex in Bootstrap?

I have a row with 3-cols containing a dropdown menu within each column. The dropdown menu appears below when an option is selected. Clicking the option button causes the height of the columns to extend, flex, or increase as intended. To achieve this effec ...

Transform JSON data into a PDF file using NodeJS

When a GET request is made to: 'http://localhost:4000/features', the response contains JSON Data with embedded HTML. I am looking to extract and save the content of the "name" and "description" fields as a PDF. Here is a sample snippet: [{"_id ...

Developing a quiz using jQuery to load and save quiz options

code: http://jsfiddle.net/HB8h9/7/ <div id="tab-2" class="tab-content"> <label for="tfq" title="Enter a true or false question"> Add a Multiple Choice Question </label> <br /> <textarea name ...

Toggle the submenu with a fade effect when jQuery is clicked

Currently, I am facing an issue with creating links that are supposed to open their respective submenus on click. However, the script I have written is opening all submenus instead of the specific ones assigned to each link. Sample HTML Code: <nav> ...

I am attempting to display text in the input box on the console, but unfortunately, I am not seeing any changes in the console when typing

I have this code, but I am not getting any output when I run it: import { restaurantList } from "../config"; import { RestrauntCard } from "./Restraunt"; const Body = () => { const searchText = "KFC"; return ( <& ...

Issue with React Router version 6: displaying an empty page

I am currently grappling with implementing react-router for my react applications. However, I am encountering issues with the routing part as it consistently displays a blank page. Below are snippets of the code from the involved files: index.js import R ...

AngularJS implementation for a confirmation dialog with data

I need help creating a confirmation dialog box for user action verification. Here's the situation: I have a table with multiple events, and users can choose to delete an event. This is how the table is structured: <tbody> <tr ng-repeat= ...

When attempting to navigate to a controller using Express.Router and Passport, encountering an undefined error with req.url.indexOf('?')

The statement "var search = 1 + req.url.indexOf('?');" throws an error indicating that it is undefined. I am currently working on creating a login/registration page using passportjs on my angular frontend. When attempting to make a post request t ...

Unable to translate text on the loading page

Encountering a peculiar issue with the translate service. Here's how I set it up: export class AppComponent implements OnInit { constructor( private translateService: TranslateService, angulartics2GoogleAnalytics: Angulartics2GoogleAnalytics ...

The search functionality for the MongoDB module is not functioning properly within my Next.js application

Working on my nextjs application, I have encountered an issue with using the mongodb node module to find all documents in one of my collections. Despite successful usage of .findOne and .updateOne for other pages like login and password reset, when I use . ...

Using a varnish proxy to transmit server-sent events

My website is currently operating behind a Varnish proxy, but I am experiencing issues with server-sent events. The connections remain open indefinitely without receiving any content, and Varnish waits for the stream to end before forwarding it to the brow ...