【发布时间】:2018-03-20 17:14:39
【问题描述】:
我正在构建一个自定义指令,我想在其中读取本机元素的一个属性 (formControlName),然后有条件地向该元素添加一个或多个属性。
但是,当我 console.log 原生元素的属性时,我得到:
未定义
这是我尝试过的:
@Directive({
selector: '[appInputMod]'
})
export class InputModDirective implements OnInit {
constructor(public renderer: Renderer2, public hostElement: ElementRef) { }
@Input()
appInputMod() { }
ngOnInit() {
console.log(this.hostElement.nativeElement.formcontrolname);
const el = this.hostElement.nativeElement;
if (el.formcontrolname === 'firstName')
{
this.renderer.setAttribute(this.hostElement.nativeElement, 'maxlength', '35');
}
}
}
如何从指令中读取此属性名称?
【问题讨论】:
-
试试
ngAfterViewInit而不是ngOnInit -
我得到了同样的结果。
-
当您在浏览器中检查标签时,标签上是否存在 formControlName 属性?顺便说一句,也许你应该使用正确的方式来获取属性。
-
是的。是的,我想这就是我要问的。看我的回答。
标签: angular angular2-directives