Is it possible to get native element for formControl?

fedor.belov picture fedor.belov · Sep 22, 2016 · Viewed 27.8k times · Source

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.

My question: is it possible to get nativeElement for formControl? I wanna do something like myFormControl.nativeElement.focus()

Answer

baHI picture baHI · Mar 24, 2018

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;
    }
}

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...