![](/img/trans.png)
[英]angular2 inject Router in component constructor error if no elvis operator
[英]Angular 2: Inject view/DOM into component constructor
我無法弄清楚如何為組件提供對其視圖的引用,以便在顯示表單時執行諸如關注輸入元素之類的操作。 我似乎無法將Element
或ng.core.ViewRef
或ng.core.View
注入構造函數。 如何訪問視圖?
在Angular 1中,我會用$ link做到這一點。
您正在尋找的可能是ElementRef
及其nativeElement
字段,但您應該避免以這種方式訪問DOM。 我認為更好的方法是添加一個模板變量,如<input #inp>
並使用@ViewChild('inp') input
訪問它。 在ngAfterViewInit
input
引用輸入元素。
我還要警告Angular中的直接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
只是為了闡述@Gunter上面的回應,你會像這樣使用@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 )"
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.