简体   繁体   English

Angular 2:将视图/ DOM注入组件构造函数

[英]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. 我似乎无法将Elementng.core.ViewRefng.core.View注入构造函数。 How can I get access to the view? 如何访问视图?

In Angular 1, I would do this with $link. 在Angular 1中,我会用$ link做到这一点。

What you are looking for is probably ElementRef and its nativeElement field, but you should avoid accessing the DOM this way. 您正在寻找的可能是ElementRef及其nativeElement字段,但您应该避免以这种方式访问​​DOM。 I think a better way is to add a template variable like <input #inp> and the access it with @ViewChild('inp') input . 我认为更好的方法是添加一个模板变量,如<input #inp>并使用@ViewChild('inp') input访问它。 In ngAfterViewInit input references the input element. ngAfterViewInit input引用输入元素。

See also angular 2 / typescript : get hold of an element in the template 另请参见angular 2 / typescript:获取模板中的元素

I would also caution against direct DOM access in Angular, but here is an example of how to do it: 我还要警告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'});
    }
}

The key idea is to inject elementRef. 关键的想法是注入elementRef。 You can then treat that as a regular DOM element. 然后,您可以将其视为常规DOM元素。 In my example here I am using jquery, but you can use standard DOM access as well. 在我的示例中,我使用的是jquery,但您也可以使用标准DOM访问。

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

Just to expound on @Gunter's response above, you would use @ViewChild like this: 只是为了阐述@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 looks like this: HTML看起来像这样:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM