[英]Angular 2- Value not updated in the input text box but its updated if used inside the curly braces
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
template: `<input [(ngModel)]="name" type="text" (input)="inputChange()">
<h3>{{name}}</h3> `
})
export class AppComponent {
name = 'Apple';
inputChange() {
this.name="Zebra";
}
}
here's my angular component. 这是我的角度分量。 I have an input box and on every key input the function "inputChange()" is called which changes my name to "Zebra",
我有一个输入框,在每个按键输入上都调用了函数“ inputChange()”,它将我的名字更改为“ Zebra”,
I have to validate the user input and return certain values for which I have to call the input event everytime they write something. 我必须验证用户输入并返回某些值,每次他们写东西时都必须为其调用输入事件。 I want the textbox value to be same as "Zebra" as my function changes the value no matter what the user types in the textbox.
我希望文本框值与“ Zebra”相同,因为无论用户在文本框中键入什么内容,函数都会更改该值。 What am i doing wrong here?
我在这里做错了什么?
You are calling inputChange()
which changes the property name to "Zebra". 您正在调用
inputChange()
,它将属性名称更改为“ Zebra”。 You already implemented Two-Way binding. 您已经实现了双向绑定。 So it is not necessary to call an event function.
因此,没有必要调用事件函数。
Change this: 更改此:
<input [(ngModel)]="name" type="text" (input)="inputChange()">
to 至
<input [(ngModel)]="name" type="text">
To validate the value, you have multiple options to do so. 要验证该值,您可以通过多种方法进行验证。 1 of them are getting the object reference of the HTML element.
其中1个正在获取HTML元素的对象引用。
This can be done by: 这可以通过以下方式完成:
<input [(ngModel)]="name" type="text" (input)="inputChange(myInput)" #myInput>
In component file: 在组件文件中:
inputChange(element: HTMLElement) {
// Some sort of check
name = element.value;
}
And remove the two-way-binding of course [(ngModel)]="name"
并删除课程
[(ngModel)]="name"
的双向绑定
将输入事件更改为键盘
<input [(ngModel)]="name" type="text" (keyup)="inputChange()">
In this case, you have to remove [(ngModel)] binding and work directly with input element. 在这种情况下,您必须删除[(ngModel)]绑定并直接使用输入元素。
You need to inject Renderer2 into your component, then update view value with 您需要将Renderer2注入组件,然后使用更新视图值
this.renderer.setProperty(element, 'value', 'Zebra');
where element is ref to input element, for example by @ViewChild 其中element是输入元素的引用,例如@ViewChild
Best practice for your task is to create custom component or directive, which implements ControlValueAccessor and uses Renderer2 inside. 任务的最佳实践是创建自定义组件或指令,该组件或指令实现ControlValueAccessor并在内部使用Renderer2。
https://almerosteyn.com/2016/04/linkup-custom-control-to-ngcontrol-ngmodel https://almerosteyn.com/2016/04/linkup-custom-control-to-ngcontrol-ngmodel
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.