2016-01-02 96 views
6

我無法弄清楚如何給組件一個對其視圖的引用,以便在顯示錶單時執行諸如關注輸入元素等操作。我不能將Elementng.core.ViewRefng.core.View注入到構造函數中。我怎樣才能訪問視圖?Angular 2:將視圖/ DOM注入到組件構造函數中

在Angular 1中,我會用$ link做到這一點。

回答

6

你在找什麼可能是ElementRef及其nativeElement字段,但你應該避免以這種方式訪問​​DOM。 我認爲更好的方法是添加一個像<input #inp>這樣的模板變量,並用@ViewChild('inp') input訪問它。在ngAfterViewInitinput引用輸入元素。

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

+0

聽起來,對。儘管如此,我正努力在ES5中找到一個例子 - 知道一個例子或資源嗎? –

+0

我不知道細節,因爲我只使用Dart,但是這應該顯示如何在ES5中使用DI http://stackoverflow.com/questions/34532138/how-to-inject-custom-service-to-angular- component-in-plain-es5-javascript –

+0

哦,對不起,我可以得到一個ElementRef,並且感謝那裏的指針!實際上,我正在尋找如何在ES5中執行'@ ViewChild',並且無法打開任何東西。 –

5

看,我也奉勸不要在角直接訪問DOM,但在這裏是如何做到這一點的例子:

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

的核心思想是注入elementRef。然後,您可以將其視爲常規DOM元素。在我的例子中,我使用的是jquery,但你也可以使用標準的DOM訪問。

更多信息:http://www.syntaxsuccess.com/viewarticle/using-jquery-with-angular-2.0

1

只是爲了闡述對@岡特的響應上面,你可以使用@ViewChild這樣的:

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

doSomething(input){ 

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

HTML如下:

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