Angular 角度2-参考<;输入>;要更改值属性的组件中的模板引用变量

Angular 角度2-参考<;输入>;要更改值属性的组件中的模板引用变量,angular,angular2-template,angular2-inputs,Angular,Angular2 Template,Angular2 Inputs,如何访问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

如何访问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.

在组件代码中:

<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.
从'@angular/core'导入{ElementRef};
...
onInput(LatlInputElement:ElementRef){
//我想在这里访问元素的value属性,然后
//修改它,使其反映回模板中。
我知道我可以将myInput.value传递到代码中,但是我需要引用,这样我也可以使用该函数来更新元素的.value属性


我想知道是否有一种方法不涉及到全局变量的双向绑定,因为我认为尽可能少的全局变量更干净。谢谢!

Angular的解决方案是将输入模型双向绑定到组件中的变量。这不会弄脏全局范围,Exp特别是,如果您使用
声明变量,请按照Typescript的文档使用

我想知道是否有一种方法不涉及对全局变量的双向绑定,因为我认为尽可能少的全局变量更干净。谢谢

我理解这一点,但是调用
ElementRef
可能是这里两个弊病中最糟糕的一个。Angular文档非常不鼓励使用它,因为Angular在处理DOM API方面已经做了很多工作

但是,您应该能够从
latlnginput.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.
我强烈建议您使用Angular的
FormBuilder
来构建一个模型驱动的表单,而不是模板驱动的表单。这是一种非常优雅的方式,可以通过编程而不是模板来控制页面上的表单值。Scotch.io有一个很好的例子,值得学习


祝你好运!

我使用反应式表单,所以我不能使用ngModel(抛出错误,我想它在使用反应式表单时不起作用),而且我不想在任何表单组中包含一个虚拟输入。我只需要它让用户键入一些内容,而不是程序创建表单的一部分(但它需要在视觉上介于其他之间,所以我不能把它放在任何地方)。我还需要能够在某些操作后设置它的值。在我的模板中,我有
。然后,我使用
@ViewChild('myInput')获取引用inputElement:ElementRef;
如果我控制台日志
this.myInput.nativeElement.value
我会得到值。但是
this.myInput.nativeElement.setAttribute('value','xxx');
什么都不做。我做错什么了吗?我假设
setAttribute
是一个有效的方法,因为在构建时没有错误我还尝试了
@ViewChild('myInput')inputElement:HTMLInputElement;
,没有
value()
setValue()
可以使用的方法。如果您正在使用
ReactiveFormsModule
并设置了FormGroup,则可以使用
将输入分配给
FormControl
。您可以通过
FormGroup
与字段交互,即
formGroupName.controls['controlName'].setValue(值)
。作为一个经验丰富的人,总是避免使用Angular与DOM进行交互。框架会为您做这件事。我知道。但这正是我试图避免的。如果输入的数据与发送到服务器无关,我认为它不应该是任何表单组的一部分,而不是必须“过滤”在将数据发送到服务器之前,请先将其删除。我不希望触碰DOM,是的……但是我如何告诉Angular“清空”呢在我选择的时候,只需使用模板引用#myInput即可将该输入输出?您不必使用模板变量,也不想使用模板变量,因为Angular不会对其调用更改检测。这可能会使页面崩溃。您可以使用
formGroupName.controls['controlName'].reset()清除该值
。无论哪种方式,您都无法通过在元素上设置属性来清除输入值。如果您不希望它出现在FormGroup中,请将其从组中取出,并对其使用双向绑定。