是否有可能为formControl获取本机元素? [英] Is it possible to get native element for formControl?

查看:64
本文介绍了是否有可能为formControl获取本机元素?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有Angular2 反应形式.我创建了formControl s,并通过[formControl]=...将其分配给输入字段.据我了解,它会创建nativeElement <-> formControl链接.

I've got Angular2 reactive form. I created formControls 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获取本机元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆