Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.1k views
in Technique[技术] by (71.8m points)

angular - Is it possible to get native element for 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.

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

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...