Ben Dilts
Ben Dilts

Reputation: 10745

Angular 2: Inject view/DOM into component constructor

I can't figure out how to give a component a reference to its view, to do things like focus on input elements when the form is shown. I can't appear to inject Element or ng.core.ViewRef or ng.core.View into the constructor. How can I get access to the view?

In Angular 1, I would do this with $link.

Upvotes: 6

Views: 6177

Answers (3)

Günter Zöchbauer
Günter Zöchbauer

Reputation: 657751

What you are looking for is probably ElementRef and its nativeElement field, but you should avoid accessing the DOM this way. I think a better way is to add a template variable like <input #inp> and the access it with @ViewChild('inp') input. In ngAfterViewInit input references the input element.

See also angular 2 / typescript : get hold of an element in the template

Upvotes: 6

TGH
TGH

Reputation: 39268

I would also caution against direct DOM access in Angular, but here is an example of how to do it:

import {Component, ElementRef, Inject, OnInit} from '@angular/core';

declare var jQuery:any;

@Component({
    selector: 'jquery-integration',
    templateUrl: './components/jquery-integration/jquery-integration.html'
})
export class JqueryIntegration implements OnInit {

    constructor(private elementRef: ElementRef) {

    }

    ngOnInit() {
        jQuery(this.elementRef.nativeElement).find('.moving-box').draggable({containment:'#draggable-parent'});
    }
}

The key idea is to inject elementRef. You can then treat that as a regular DOM element. In my example here I am using jquery, but you can use standard DOM access as well.

More info: http://www.syntaxsuccess.com/viewarticle/using-jquery-with-angular-2.0

Upvotes: 6

Jon
Jon

Reputation: 7918

Just to expound on @Gunter's response above, you would use @ViewChild like this:

@ViewChild('myElem') myInput : ElementRef;
inputVal:string;

doSomething( input ){

  let startCursor = this.myInput.nativeElement.selectionStart;
  this.myInput.nativeElement.setSelectionRange(startCursor-1, startCursor-1);
}

html looks like this:

 <input #myElem type="text" [(ngModel)]="inputVal" maxlength="5" (keyup)="doSomething( myElem )" 

Upvotes: 1

Related Questions