我不知道如何为组件提供对其视图的引用,以及在显示表单时如何关注输入元素。我似乎无法将Element
、ng.core.ViewRef
或ng.core.View
注入构造函数。如何访问视图?
在Angular 1中,我将使用$link来完成此操作。
您要查找的可能是ElementRef
及其nativeElement
字段,但应避免以这种方式访问DOM。我认为更好的方法是添加一个像<input #inp>
这样的模板变量,并用@ViewChild('inp') input
访问它。在ngAfterViewInit
中,input
引用输入元素。
另请参阅angular 2/typescript:获取模板中的元素
我也会警告不要在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 )"