考虑一下我的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元素上 而不是输入元素上 然后创建一个myCustomDirectivePlaceholder组件 它注入myCustomDirective来获取所需的字符串 然后像这样使用它们
<md-input-container myCustomDirective>
<input mdInput>
<md-placeholder>
<myCustomDirectivePlaceholder></myCustomDirectivePlaceholder>
</md-placeholder>
</md-input-container>