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

问题描述

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

I've got Angular 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 want to 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;
    }
}

因此,如果在主模块中提供并导出此指令,它将自定义 nativeElement 属性附加到所有 FormControl.

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 获取本机元素?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-17 09:18