angular2 - 引用组件中的 <input> 模板引用变量来更改 value 属性

标签 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 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 - 引用组件中的 &lt;input&gt; 模板引用变量来更改 value 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42075117/

相关文章:

angular - 为什么我的 TestBed 提供者不覆盖实际服务?

javascript - 选择使用 Angular 2 显示所选值的对象

angular - 根据注入(inject)的配置编译模板

angular - 如何将字符串传递给 Angular 2 (click) 函数?

angular - @Input等装饰器和继承

angular - 从 Angular 2 中的子组件更新父组件属性

angular - 构建 Angular 库时防止 SCSS 处理

angular - Angular2中LocationStrategy实例化时出错

javascript - 如何通过 Angular 中的异步 base64 字符串显示图像