【发布时间】: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