typescript 如何设置值输入字段 Ionic 2

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/40512390/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-09 07:28:06  来源:igfitidea点击:

How to set Value Input field Ionic 2

typescriptdominputionic2refresh

提问by Luca Trembon

I have a tiny question.

我有一个小问题。

I'm using this HTML code:

我正在使用这个 HTML 代码:

<ion-input id="amount" type="number" ></ion-input>

<button (click)="setinput()">Set Value</button>

<button (click)="setinput()">Set Value</button>

And this TS code:

而这个 TS 代码:

setinput(){
var input= document.getElementById("amount") as HTMLInputElement;
input.value=42;
console.log("amount");
console.log(input.value);
}

My console tells me, that the number got changed. But the updated value wont be displayed in my input field. Do you have any suggestions?

我的控制台告诉我,号码已更改。但是更新后的值不会显示在我的输入字段中。你有什么建议吗?

Thanks in Advance!

提前致谢!

L. Trembon

L.特伦本

回答by Andreas Gassmann

You can do it like that:

你可以这样做:

page.html

页面.html

<ion-input id="amount" type="number" [(ngModel)]="value"></ion-input>
<button (click)="setInput()">Set Value</button>

page.ts

页面.ts

export class Page {
  value: number = 0; // Default is 0

  constructor() {}

  setInput() {
    this.value = 42;
  }
}

By using [(ngModel)]="value"you bind the valuevariable to that input field. That way it is always updated. If you change it in the UI, it is immediately updated "in the code". And when you update it in your code, it automatically updates in the UI.

通过使用[(ngModel)]="value"您将value变量绑定到该输入字段。这样它总是更新。如果您在 UI 中更改它,它会立即在“代码中”更新。当您在代码中更新它时,它会在 UI 中自动更新。

You should probably read an Angular 2 tutorial before you continue working on your app. Angular provides many tools to make that sort of thing a lot easier.

在继续开发您的应用程序之前,您可能应该阅读 Angular 2 教程。Angular 提供了许多工具来让这种事情变得更容易。