问题描述
我有Angular2 反应形式.我创建了formControl
s,并通过[formControl]=...
将其分配给输入字段.据我了解,它会创建nativeElement <-> formControl
链接.
I've got Angular2 reactive form. I created formControl
s and assigned it to input fields by[formControl]=...
. As I understand it creates nativeElement <-> formControl
link.
我的问题:是否可以为formControl
获取nativeElement
?我想做类似myFormControl.nativeElement.focus()
My question: is it possible to get nativeElement
for formControl
? I wanna do something like myFormControl.nativeElement.focus()
推荐答案
下面的代码不适用于纯ngModel绑定,因此我做了很多实验.最近,马克西米利安·施瓦兹穆勒(Maximillian Schwarzmuller)确认的人也应该是这样的人:
The code below does not work with pure ngModel binding, so I did a lot of experiments. Latest, also confirmed by Maximillian Schwarzmuller should be the one:
@Directive({
selector: '[ngModel], [formControl]', // or 'input, select, textarea' - but then your controls won't be handled and also checking for undefined would be necessary
})
export class NativeElementInjectorDirective {
constructor(private el: ElementRef, private control : NgControl, @Optional() private model : NgModel) {
if (!! model)
(<any>model.control).nativeElement = el.nativeElement;
else
(<any>control).nativeElement = el.nativeElement;
}
}
因此,如果在主模块中提供并导出了此指令,则它将向所有FormControl附加自定义nativeElement属性.
So if this directive is provided and exported in the main module, it will attach a custom nativeElement property to all FormControl.
可惜的是没有开箱即用...
It's a shame it's not coming out-of-the box...
这篇关于是否有可能为formControl获取本机元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!