自定义指令可以使用 Angular Material 为输入设置占位符吗?

Can a custom directive set the placeholder for an input using Angular Material?

考虑一下我的 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 更改检测策略(如果有任何不同的话)。

这似乎可行,尽管它很老套(因为 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>