What is the best way to change the style of an HTML element, such as its color, from within a TypeScript file?

Within the HTML section of my page, I currently have the following code snippet:

<ion-row padding>
    <ion-input [(ngModel)]="addressSearchfield" name="addressSearch'></ion-input>
</ion-row>

Now, I am looking to adjust the color of the ion-input element in the TypeScript part of my page.

To extract the stored value, I can use code similar to this:

addressSearchfield: string;
//...
console.log(this.addressSearchfield);

I initially attempted to refer to the element and modify its properties with something like this:

addressrow: any;
// ...
this.addressSearch.color = '#FFFFFF';

However, this resulted in the error message

Cannot set property 'color' of undefined
.

What is the correct approach for achieving this?

Answer №1

An alternative approach in the context of Ionic would involve utilizing CSS properties to achieve the desired outcome. As outlined in the documentation, the ion-input component includes a CSS property specifically for setting the text color:

CSS Custom Properties

Name    | Description
--------|------------------------
...
--color | Color of the input text
...

To implement this, you can define a new custom CSS property within the variables.scss file like so:

:root {

  // ...

  --input-custom-color: blue; // default color for the input

}

Subsequently, within your page's styling, you can specify that the input should utilize this defined CSS property:

// my-page.page.scss

[name="addressSearch"] {
  --color: var(--input-custom-color);
}

This setup allows you to easily modify the color by simply altering the value of the CSS property from within the component:

// Angular
import { Component, Inject } from "@angular/core";
import { DOCUMENT } from '@angular/platform-browser';

// Ionic
import { DomController } from '@ionic/angular';

@Component({
  selector: "app-my-page",
  templateUrl: "my-page.page.html",
  styleUrls: ["my-page.page.scss"]
})
export class MyPage {

  constructor(
    private domCtrl: DomController,
    @Inject(DOCUMENT) private document
  ) {}

  public changeColor(aColor: string): void {

    // Notify Ionic about DOM modifications
    this.domCtrl.write(() => {

      // Update the CSS property value
      this.document.documentElement.style.setProperty('--input-custom-color', aColor);
    });
  }
}

By invoking this.changeColor('green');, for instance, you can dynamically adjust the input's color in the UI. This method offers the benefit of centralized control over styling across various inputs within your application, eliminating the need to directly manipulate individual DOM elements.

It's worth noting that this approach is not limited to color changes alone but can be extended to customize other styles as well, whether through specific CSS properties or general attributes like

color: var(--input-custom-color);

Answer №2

Indeed, the solution provided by Heretic Monkey does function as intended.

document.querySelector('[name="addressSearch"]').style.color = '#FFFFFF';

However, I am encountering a red squiggle in my editor due to the style element.

After some tinkering inspired by the previous code:

addressSearch: HTMLElement;
// ...
this.addressSearch= document.querySelector('[name="addressSearch"]');
this.addressSearch.style.backgroundColor = '#FFFFFF';

I achieve the same result but with a more pleasing reaction from my editor.

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

Different categories combined into a singular category

Trying to define a type that can be one of two options, currently attempting the following: type TestConfig = { file: string; name: string; } type CakeConfig = { run: string; } type MixConfig = { test: TestConfig | CakeConfig }; const typeCheck: M ...

A static method written in Typescript within an abstract class for generating a new instance of the class itself

Imagine I have abstract class Foo { } class Bar1 extends Foo { constructor(someVar) { ... } } class Bar2 extends Foo { constructor(someVar) { ... } } I want to create a static method that generates an instance of the final class (all construct ...

Leveraging ts-loader alongside strip-loader in Webpack

I am currently facing an issue with strip-loader in my Typescript project that is built with Webpack. The ts-loader statement in my project is as follows: { test: /\.ts$/, loader: 'babel-loader?presets[]=es2015!ts-loader' } Everything see ...

Retrieving All Relationship Information in AdonisJS

Is there a way to fetch all the data, including related data in AdonisJS? I am looking to retrieve user data from the User Model along with its relationships in the Post Model. Get All Users public async getUsers({ response }: HttpContextContract) { ...

Component in Angular with an empty variable in TypeScript

I'm encountering an issue on my web page where I have a loop calling a component multiple times. I successfully pass data to the component, but the problem arises when I try to display the value of an object in the component. In the component's H ...

Substitute a value in a list with a distinctive identification code

I have a list of dailyEntries. Each entry has a unique identifier called id. I am given an external dailyEntry that I want to use to replace the existing one in the array. To achieve this, I can use the following code: this.dailyEntries = this.dailyEntri ...

Navigating an array and organizing items based on matching properties

When I receive an array that looks like this: errors = [ { "row": 1, "key": "volume", "errorType": "Data type", "expectedType": "number", &quo ...

Is it possible to assign an interface to an object property in TypeScript?

I am currently working with an object that looks like this: export class Section{ singleLabel:string; pluralLabel:string; index:number; dataInterface:Interface; } My goal is to assign an interface to the dataInterface field, as I need to use the S ...

The Intersection Observer API is caught in a never-ending cycle of rendering

I am experimenting with the intersection observer API in order to selectively display elements in a CSS grid as the user scrolls, but I seem to have run into a problem of encountering an endless rendering loop. Below is the code snippet I am working with. ...

The name 'undefined' was not found in the union type

I need to declare a variable: Id: string | string[] | undefined; But I'm facing an error TS2304: Cannot find name 'undefined'. Even though Basic Types states that undefined is a valid type in TypeScript. Advanced Types explores union ...

Increase the ngClass attribute's value

Is there a way to automatically increment a numeric value in a class using the ngClass directive? For example, can we achieve something like this: <some-element [ngClass]="'class-*'">...</some-element>, where the asterisk (*) will in ...

The function 'toLowerCase' cannot be found for the type 'string | number | string[]'. Similarly, the function 'toLowerCase' cannot be found for the type 'number'

Currently, I am working on a Laravel project using Laravel Mix. I am attempting to create a table with filter functionality. However, when I insert the following code into my TS file: import $ from 'jquery'; import 'bootstrap'; $(() = ...

Issue in insert.php file: stdClass::$variable property is undefined when using Ionic, Angular, and PHP together

There are three files. Once the submit button is clicked on the Ionic page, all inputs will be sent to the controller, which will then parse them to insert.php. The form input data is saved successfully when only using HTML (without Ionic content), however ...

When comparing TypeScript index signatures to Record<Keys, Type> return type, the focus is on handling objects with unspecified properties

I have a function called getQueryParams that takes a string as input and returns an object with unknown properties: function getQueryParams(s) { if (!s || typeof s !== 'string' || s.length < 2) { return {} } return s .substr(1) ...

Retrieve data from a JSON object within an HTML document

How do I display only the value 100 in the following div? <div> {{uploadProgress | async | json}} </div> The current displayed value is: [ { "filename": "Mailman-Linux.jpg", "progress": 100 } ] Here is my .ts file interface: interface IU ...

In a standalone script, the error message "ReferenceError: exports is not defined in ES module scope" is encountered

When I execute the script using npx ts-node -i --esm --skipProject -T .\seed.ts import { readdir, readFile } from "node:fs/promises" async function readFeedsFromFiles() { const data = await readdir("./seedData/feeds", { ...

Troubleshooting Angular: Implementing scrollIntoView on route change without using setTimeout within ngAfterViewInit

I am currently working on an Angular component where I need to implement scrollIntoView functionality when the route changes. Below is a snippet of the relevant code from my component: @ViewChild('structure') structure: ElementRef | undefined; le ...

Find the sum of individual data points in chart.js by taking into consideration their respective

I created a line chart using the Chart.js library. My goal is to calculate the weighted sum when hovering over a specific data point, based on the difference between that point and its neighboring points. For instance, if point[0] = 5 with weight 2, point[ ...

Type void does not have a property of type forEach

I've encountered similar questions before, such as this one: (forEach Typescript TS2339 "does not exist on type 'void'") Despite that, I'm still struggling to solve my specific issue. ngOnInit() { var __this = this; this ...

Transforming "larger" items into "smaller" items using Typescript

I am experiencing challenges when trying to assign larger objects into smaller ones. To illustrate this issue, I will provide a simple example: Let's say I have defined the Typescript interface: export interface CrewMember { name: string; orga ...