Angular input material with a stylish twist

How can I style all inputs on the Angular Material input component (matInput) using Typescript?

I attempted to implement this solution, but it only affects the first element.

ngAfterViewInit () {
    const matlabel = this.elRef.nativeElement.querySelector('.mat-form-field-label');
    matlabel.style.color = 'white';
  }

=====================

<form [formGroup]="form" (ngSubmit)="login()">
      <table cellspacing="0" class="tb-login">
        <tr>
          <td>
            <mat-form-field class="form-login">
              <input matInput type="text" placeholder="Login" formControlName="login"  class="input-login"/>
            </mat-form-field>
          </td>
        </tr>
        <tr>
          <td>
            <mat-form-field class="form-login">
              <input matInput type="password" placeholder="Password" formControlName="password" class="input-login"/>
            </mat-form-field>
          </td>
        </tr>
        <tr>
          <td>
            <button mat-raised-button type="submit" class="btn_login">Login</button>
          </td>
        </tr>
      </table>
    </form>

Angular v7 Material Angular v7

Your suggestions are much appreciated.

Answer №1

To achieve this, utilize the Renderer2 in conjunction with ViewChild.

The Renderer2 provides Platform Agnostic APIs for making DOM modifications and is recommended over native document APIs.

You can include Renderer2 as a dependency in your Component and then invoke the setStyle method on it by specifying the target element, style attribute name ('background'), and its value (for example, 'red').

Give this code snippet a try:

import { Component, ViewChild, Renderer2 } from '@angular/core';
import { MatInput } from '@angular/material/input';

@Component({...})
export class InputOverviewExample {

  @ViewChild('food') matInput: MatInput;

  constructor(private renderer: Renderer2) {}

  ngAfterViewInit() {
    this.renderer.setStyle(this.matInput.nativeElement, 'background', 'red');
  }

}

In your Template, create template variable(s) similar to how it's done with the input tag using the name food. This name corresponds to @ViewChild('food'):

<form class="example-form">
  <mat-form-field class="example-full-width">
    <input #food matInput placeholder="Favorite food" value="Sushi">
  </mat-form-field>

  <mat-form-field class="example-full-width">
    <textarea matInput placeholder="Leave a comment"></textarea>
  </mat-form-field>
</form>

You can also check out a Working Sample StackBlitz for reference.

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

What are the benefits of maintaining a property as non-observable instead of observable in knockout.js?

In my TypeScript project utilizing Knockout.js, I have a class with several properties. One of these properties is 'description', which is not directly tied to the DOM but needs to be used in popups triggered by certain mouse events (such as butt ...

Can you explain the distinction between any[] and [] in TypeScript?

Here is an example that successfully works: protected createGroups(sortedItems: Array<TbpeItem>): any[] { let groups: any[] = []; return groups; } However, the second example encounters a TypeScript error: type any[] not assignable to ...

Using Firebase: retrieving getAdditionalUserInfo in onCreate of a Firebase Cloud function

Can anyone help me figure out how to retrieve extra data from a SAML login provider in the backend (firebase functions)? I can see the data on the client side but I'm struggling to access it in the backend. I've specified these dependencies for ...

Exploring the zoom functionality and tooltip features of Area Range charts in Highcharts

I need help with a couple of things on the high charts area range chart: I am trying to enable zooming into the y-axis of the chart, but I am facing difficulties. Can anyone suggest how this can be achieved? Below is the link to my jsfiddle with the sam ...

Error encountered in Angular/Ramda while using mapAccum with an array of objects in Typescript

I am having difficulties implementing Ramda in an Angular 6 / TypeScript environment. "ramda": "^0.25.0", "@types/ramda": "^0.25.24" This is how I have started: const addP = (p1,p2) => ({ x: p1.x+p2.x,y: p1.y+p2.y }); const accum = (a,b) => [add ...

Encountering issues with package resolution in VS Code while setting up a monorepo with yarn workspaces, Vite, React, and

I recently set up a monorepo using yarn@3 workspaces. Here is the structure of my root package.json: { "name": "hello-yarn-workspaces", "packageManager": "<a href="/cdn-cgi/l/email-protection" class="__cf_email__" ...

Having trouble retrieving the parameter sent through the router in Ionic 4

I am facing an issue in my Ionic 4 project where I am trying to send a parameter using the router but unable to retrieve it on the other page. Here is how my tabs.router.module.ts looks like: { path: 'tab2', children: [ { ...

Unable to locate module '@angular/core' while utilizing PrimeNG

After installing PrimeNg, I attempted to use the sidebar component in my project. However, upon running the project, an error occurred: ERROR in /home/haddad/projects/node_modules/primeng/components/sidebar/sidebar.d.ts (1,97): Cannot find module '@a ...

Error: Angular 4 component failed to load

It seems that the route /users is not functioning as expected; instead of loading the UsersComponent, it loads the AppComponent. Why is the /users route not loading the correct component? Here is a snippet from app.module.ts: import { Brows ...

Need help in NestJS with returning a buffer to a streamable file? I encountered an error stating that a string is not assignable to a buffer parameter. Can anyone provide guidance on resolving this issue?

The issue description: I am having trouble returning a StreamableFile from a buffer. I have attempted to use buffer.from, but it does not seem to work, resulting in the error message below. Concern in French language: Aucune surcharge ne correspond à cet ...

JavaScript - Trouble encountered while trying to use splice to insert one array into another array

I've been working on creating a Cache Hashtable using JavaScript. When I use the code cache.splice(0,0, ...dataPage);, it inserts my data starting from the first position up to the length of dataPage. Assuming that my dataPage size is always 10. Th ...

Angular // binding innerHTML data

I'm having trouble setting up a dynamic table where one of the cells needs to contain a progress bar. I attempted using innerHTML for this, but it's not working as expected. Any suggestions on how to approach this? Here is a snippet from my dash ...

Is it possible to align the radio-button label above the radio-button in Angular Material 2?

Currently, I am utilizing angular material 2 (material.io) and attempting to position the label of the md-radio-button above the radio button itself. Here's an illustration: View Radio Buttons The official documentation mentions that you can easily ...

Error: zsh is unable to locate the command, even after defining it in package.json bin and installing it globally

I attempted to create a command-line application using TypeScript. Below is the code I have written: //package.json { "name": "jihea-cli", "version": "1.0.0", "description": "", "main": "index.ts", "bin": { "cli": "./bin/index.ts" }, // ...

Personalized Titles for Angular Material Elements

I am new to using angular and angular material, and I find it a bit frustrating that each angular-material component starts with mat. For example: <mat-sidenav-container> <mat-sidenav>...</mat-sidenav> <mat-sidenav-content>...& ...

Executing a method of another component in Angular2

In my Angular2 application, I have created a Header component that is rendered within the main App component. Now, I am faced with the challenge of placing a submit button from another Form component into the Header. How can I achieve this? I find myself ...

Is it possible to include multiple eventTypes in a single function call?

I have created a function in my service which looks like this: public refresh(area: string) { this.eventEmitter.emit({ area }); } The area parameter is used to update all child components when triggered by a click event in the parent. // Child Comp ...

Update the child component whenever there are changes in the variables of the parent component in Angular 2

I've implemented a MasterComponent that loads the header, footer, sidebar, and more. The header includes a dropdown with options that are set once the user logs in. I need the header to remain constant even when navigating to different routes, each lo ...

The initial Get request does not receive data upon first attempt

In the process of developing an Angular project, I am faced with the task of retrieving data from my backend by making requests to an API. However, before the backend can fetch the required data, certain parameters must be sent through a post request. Once ...

Issues with NPM start arise moments after incorporating create react app typescript into the project

I've encountered an error while trying to initiate my create react app with Typescript. Despite following all the necessary steps, including adding the .env file (with SKIP_PREFLIGHT_CHECK=true) and updating/reinstalling NPM, I keep facing this issue. ...