【问题标题】:Style input material angular风格输入材料角度
【发布时间】:2019-05-07 07:05:41
【问题描述】:

关于角度材质和输入组件(matInput)如何修改打字稿中所有输入的样式?

我正在尝试这种方式,但它只修改了第一个元素。

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

我将不胜感激。

【问题讨论】:

标签: angular typescript angular-material


【解决方案1】:

使用Renderer2ViewChild 来执行此操作。

Renderer2 提供了与平台无关的 API 来修改 DOM,应该使用与原生的 document API 相对的 API。

您可以在组件中注入Renderer2 作为依赖项,然后在其上调用setStyle 方法,传递您要设置样式的元素、样式名称('background') 及其值(red 在我的例子中)。

来,试试看:

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');
  }

}

在您的模板中,创建模板变量,就像我在 input 标记上所做的那样,名称为 food。这就是我在@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>

这里有一个Working Sample StackBlitz 供您参考。

【讨论】:

  • 非常好!在此示例中,我有两个字段/输入是否需要为每个字段/输入引用?示例 # field1 和 # field2 或者有没有办法将样式应用于所有相关的 html 输入?
  • 我实际上尝试过使用MatInput,但显然不是这样,因为通过ViewChild 访问它会返回undefined。所以是的,如果您有两个字段,那么您只需在组件类上定义两个属性即可。
  • 好的!这样我看到我可以改变背景的颜色,但是你能告诉我如何改变标签和输入线的颜色吗?
猜你喜欢
  • 1970-01-01
  • 2017-01-03
  • 2015-05-19
  • 2015-09-10
  • 2018-07-20
  • 1970-01-01
  • 2018-12-14
  • 2018-06-22
相关资源
最近更新 更多