在Angular 2中使用Typescript选择输入内的文本 [英] Select the text inside an input using Typescript in Angular 2
问题描述
I'm trying to do exactly what is described in this post, but in Angular2.
用户单击触发器后,在输入中基本上使用javascript函数.setSelectionRange(start, end);
.我找不到任何使用Typescript复制此行为的方法.
Basically use the javascript function .setSelectionRange(start, end);
in an input after a user clicks on a trigger. I can't find any way to replicate this behaviour using Typescript.
谢谢.
推荐答案
我找不到使用Typescript复制此行为的任何方法.
I can't find any way to replicate this behaviour using Typescript.
TypeScript只是JavaScript.我怀疑您是想说Angular2
(该帖子是Angular1).
TypeScript is just JavaScript. I suspect you mean to say Angular2
(that post is Angular1).
您需要掌握dom元素(您似乎正在为此而苦苦挣扎).在您的控制器中,您需要注入ElementRef
.例如. @Inject(ElementRef) elementRef: ElementRef,
You need to get a hold of the dom element (which is what you seem to be struggling with). In your controller you need to inject ElementRef
. E.g. @Inject(ElementRef) elementRef: ElementRef,
一旦有了元素,您就可以遍历它并进行所需的任何dom访问/手动操作.
Once you have the element you can traverse it and do whatever dom access / manual manipulation you need to do.
文档: https://angular.io/docs/js/latest/api/core/ElementRef-class.html
示例: https://stackoverflow.com/a/32709672/390330
import {Component, ElementRef} from 'angular2/core';
@Component({
selector:'display',
template:`
<input #myname (input) = "updateName(myname.value)"/>
<p> My name : {{myName}}</p>
`
})
class DisplayComponent implements OnInit {
constructor(public element: ElementRef) {
this.element.nativeElement // <- your direct element reference
}
ngOnInit() {
}
}
这篇关于在Angular 2中使用Typescript选择输入内的文本的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!