如何访问 Angular2 组件中元素的 value 属性?
在模板中:
<input #myInput (keyup.enter)="onInput(myInput)"/>
在组件代码中:
import {ElementRef} from '@angular/core';
...
onInput(latLngInputElement: ElementRef) {
// I want to access the value property of the <input> element here, and
// modify it so that it is reflected back in the template.
我知道我可以将 myInput.value 传递到代码中,但我需要引用,以便我还可以使用该函数来更新元素的 .value 属性。
我想知道是否有一种方法可以做到这一点,并且不涉及到全局变量的两种方式绑定(bind),因为我认为使用尽可能少的全局变量会更干净。谢谢!
最佳答案
Angular 对此的解决方案是将输入模型双向绑定(bind)到组件中的变量。这不会涉及弄脏全局范围,特别是如果您按照 Typescript 的文档使用 let
声明 var。
I'd like to know if there is a way to do this that does not involve two way binding to a global variable, because I think it is cleaner to have as few globals as possible. Thanks!
我理解这一点,但调用 ElementRef
可能是两害之中更糟糕的一个。 Angular 文档非常不鼓励使用它,因为 Angular 已经做了很多处理 DOM API 的事情。
但是,您应该能够从latLngInputElement.value
获取值。
如果您正在寻找更清洁的解决方案:
我强烈建议您查看 Angular 的 FormBuilder
来构建一个模型驱动表单,而不是模板驱动表单。这是一种非常优雅的方式,可以通过编程方式控制页面上的表单值,而不是在模板上。 Scotch.io 有一个 excellent blog post在上面。非常值得学习。
祝你好运!
关于angular2 - 引用组件中的 <input> 模板引用变量来更改 value 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42075117/