【问题标题】:Can a custom directive set the placeholder for an input using Angular Material?自定义指令可以使用 Angular Material 为输入设置占位符吗?
【发布时间】:2017-10-25 12:32:23
【问题描述】:

考虑一下我的 html:

  <md-input-container>
    <input mdInput myCustomDirective
      formControlName="email"
    >
  </md-input-container>

在我的自定义指令中,我想设置占位符。

我尝试过这样的幼稚代码但失败了:

@Directive({
  selector: '[myCustomDirective]',
})
export class MyCustomDirective implements OnInit, AfterViewInit {


  constructor(
    private elementRef: ElementRef,
    private renderer2: Renderer2,
  ) {}

  ngAfterViewInit() {
    this.renderer2.setAttribute(
      this.elementRef.nativeElement,
      'placeholder',
      'test',
    );
  }
}

我是否将 setAttribute 代码放在构造函数或任何生命周期挂钩中似乎并不重要。

还有其他我没有想到的方法吗?

我正在使用响应式表单和 OnPush 更改检测策略,如果这有什么不同的话。

【问题讨论】:

  • 你可以试试这个而不是所有 elementRef/renderer 的东西吗? @HostBinding('attr.placeholder') placeholder = 'test';
  • 通常情况下,我认为这会奏效。实际上,它将输入元素的占位符属性设置为“测试”。但这还不足以让有角材料实际显示占位符。我需要弄清楚如何让有角度的材料知道占位符并使用它。我希望有一些角度材料 api 来支持这一点,但我还没有找到任何东西。

标签: angular forms angular-material directive placeholder


【解决方案1】:

这似乎可行,虽然它很 hacky(因为 MdInputDirective 的占位符字段实际上是一个输入)。虽然,任何命令式的解决方案对我来说都很糟糕。

import {MdInputDirective} from '@angular/forms';

@Directive({
  selector: '[myCustomDirective]'
})
export class MyCustomDirective {
  constructor(@Self() private input: MdInputDirective) {}

  ngAfterViewInit() {
    this.input.placeholder = 'test';
  }
}

另一种解决方案可能是这样的:将指令放在 md-input-container 元素而不是 input 元素上,然后创建一个 myCustomDirectivePlaceholder 组件,该组件注入 myCustomDirective 以获取所需的字符串,并像这样使用它们:

<md-input-container myCustomDirective>
  <input mdInput>
  <md-placeholder>
    <myCustomDirectivePlaceholder></myCustomDirectivePlaceholder>
  </md-placeholder>
</md-input-container>

【讨论】:

  • 完美!我忘了@Self,巧妙的把戏。你的第一个选择正是我想要的。我应该提到我的指令的目的之一是减少模板中所需的 html 样板数量。
  • 实际上,我认为它可以在没有 Self 的情况下工作,但是使用 Self 将依赖注入限制为仅在同一元素上的东西,所以它“更安全”(并且有点自我记录)。 “宿主”也是如此。
  • 是的,确认工作没有@Self,所以我想这里的技巧是可以像这样注入指令。太棒了,我学到了一些东西。谢谢。
猜你喜欢
  • 2021-05-18
  • 1970-01-01
  • 2015-01-26
  • 2016-07-18
  • 1970-01-01
  • 1970-01-01
  • 2014-01-10
  • 2021-09-07
  • 1970-01-01
相关资源
最近更新 更多