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

How can we leverage the nullish coalescing operator (`??`) when destructuring object properties?

When working with ReactJS, I often find myself using a common pattern of destructuring props: export default function Example({ ExampleProps }) { const { content, title, date, featuredImage, author, tags, } = ExampleProps || {}; ...

Strategies for Managing Output Event Prioritization in Angular Using RxJs Based on Trigger Sequence

Within my Angular Application, there is a widget with two event outputs originating from a third-party library. Unfortunately, I am unable to modify its behavior. <myWidget (onAlwaysEvent)="onAlwaysEvent($event)" (onSometimesEvent)="onSometimesEven ...

Establishing specific categories for a universal element

I have been working on creating an input component that functions as a custom select for enums in my application. I have tried defining them for different types using concise one-liners but have run into various typing issues. Here is what I have so far: ...

Connecting the SelectedItem of a listbox in ngPrime to an Observable Collection in Angular2

I am facing an issue while trying to use the ngPrime listbox in Angular2. I have a scenario where I am fetching an array of objects from Firebase as an observable and attempting to display it correctly in the listbox. <div *ngIf="addContactDialogVisibl ...

What is the proper way to specifically define a new property on the `global` object in TypeScript?

I want to define a type signature for the variable below: (global as any).State = { variables: {}, }; How can I declare the type of State? If I try (global as any).State: Something = ..., the compiler displays an error message saying ; expected. It se ...

Is it feasible to alter the TypeScript interface for the default JavaScript object (JSON)?

When dealing with cyclic objects, JSON.stringify() can break (as mentioned in https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Errors/Cyclic_object_value) An alternative solution suggested in the same article is to use 'cycle.js&apos ...

Generate a new Angular component by only creating the TypeScript file

As a newcomer to Angular, I recently purchased the Metronic theme. After installing all necessary components, including the latest version of angular CLI, I encountered an issue. Whenever I run the command ng generate component test, it only creates a test ...

exit out of React Dialog using a button

I have a scenario where I want to automatically open a dialog when the screen is visited, so I set the default state to true. To close the dialog, I created a custom button that, when clicked, should change the state to false. However, the dialog does no ...

A step-by-step guide on reading/loading a JSON file using Typescript

I'm fairly new to Typescript and I'm attempting to parse a simple JSON file using Typescript. After searching online and testing different solutions, I still haven't been able to find a straightforward code snippet that reads a local JSON fi ...

Uploading Files to the Server with Angular 2 and ExpressJS

In my Angular-2 project, I am currently working on uploading files to the server. The code snippet provided below showcases how the file is uploaded: My main question pertains to linking these uploaded files to specific mongodb documents. How can I achiev ...

How to properly handle Angular routing errors and best practices?

Currently, I have been delving into learning Angular to integrate with my Ruby on Rails application. However, I have encountered some challenges specifically related to routing. Here is a snippet from my app.routing file: import { NgModule } from '@ ...

Issue with the integration of Angular and Java Jersey API arises when attempting to encode utf-8 whitespaces at the end, resulting in invalid JSON

I'm facing an issue with Angular while making an HTTP GET request. It throws a "Http failure during parsing" error because the JSON response contains whitespace characters at the end. I find it puzzling why the server is returning them. Is there a wa ...

Designing a personalized carousel component in Angular

Looking to replicate this design, any tips? I'm aiming for a carousel layout with developers listed in a project, where the center item is larger than the others. Any guidance on how to achieve this look? ...

Want to learn how to integrate React-pdf (@react-pdf/renderer) with TypeScript on NodeJS and Express JS?

I am encountering difficulties running React-Pdf (@react-pdf/renderer) with TypeScript on an Express JS server. I have attempted to use babel but encountered errors that I cannot resolve. build error error error You can find the Github repository for t ...

Effective Strategies for Managing Real-Time Messaging in a MEAN Stack Application

I'm looking to create a MEAN Stack application, but I'm struggling to find clear guidance on how to implement live messaging similar to applications like WhatsApp or Facebook Messenger. At first, I considered using the setTimeout function and ma ...

Angular2 allows you to create pipes that can filter multiple values from JSON data

My program deals with an array of nested json objects that are structured as follows: [{name: {en:'apple',it:'mela'}},{name:{en:'coffee',it:'caffè'}}] I am looking to implement a pipe that can filter out objects b ...

Troubleshooting issue with image dimensions in Angular within CKEditor content

One issue I am facing is with CKEditor, where images inserted into Rich Text Fields have their height and width attributes set in a CSS style tag. For example: <img alt="" src="https://something.cloudfront.net/something.jpg" style="height:402px; ...

Integrate jQuery-ui into your Angular 5 application

Having some trouble integrating jquery-ui into my Angular 5 project. I need to use a feature that requires jquery-ui, but I keep encountering this error: TypeError: WEBPACK_MODULE_10_jquery(...).droppable is not a function I initially attempted to plac ...

Is there a way to define one type parameter directly and another type parameter implicitly?

I am currently utilizing a UI-library that offers an API for constructing tables with a structure similar to this: type Column<Record> = { keys: string | Array<string>; render: (prop: any, record: Record) => React.ReactNode; } The l ...

Include asterisk symbol at the end of a web address following a designated keyword

I currently have a URL structured in the following way: https://localhost:8080/user/login But, there is an option to manually add query parameters which could result in a URL like this. https://localhost:8080/user/login?ten=123456 This leads me to seek ...