typescript 如何使用打字稿在 angular 4 中设置文本框值?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/48114855/
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
How to set text box value in angular 4 using typescript?
提问by JanithCW
How to set text box value in Angular 4 using TypeScript? I tried in this way but it doesn't work.
如何使用 TypeScript 在 Angular 4 中设置文本框值?我以这种方式尝试过,但它不起作用。
app.component.html
应用程序组件.html
<form class="example-form">
<mat-form-field class="example-full-width">
<input matInput class='aaaa' placeholder="Favorite food" [(ngModel)]="form1" value="{{setTextBoxValue}}">
</mat-form-field>
<button (click)='clickMe()'>Click Me</button>
</form>
app.component.ts
app.component.ts
import {Component, OnInit} from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
title = 'app';
clickMe() {
setTextBoxValue: string = "new value";
}
}
回答by Milo
Remove value="{{setTextBoxValue}}"
and just use [(ngModel)]
. For example if you have private inputVar: string;
in your component (.ts
) then the element would look like:
删除value="{{setTextBoxValue}}"
并使用[(ngModel)]
. 例如,如果您private inputVar: string;
的组件 ( .ts
) 中有元素,则该元素将如下所示:
<input matInput placeholder="Input" [(ngModel)]="inputVar">
In the component (.ts
) you could have:
在组件 ( .ts
) 中,您可以:
constructor() { this.inputVar = "initial value" }
And then a button with (click)
event like you have:
然后是一个(click)
像你这样的事件按钮:
<button type="button" (click)="changeInputVar()">Test Change</button>
And again in your .ts
you have the changeInputVar()
defined:
再次在您.ts
的changeInputVar()
定义中:
private changeInputVar(): void {
this.inputVar = "changed";
}
Here is a demo.
这是一个演示。
回答by Sajeetharan
just set the model value inside the function,
只需在函数内设置模型值,
this.fomr1 = "new value";
also make sure you have the form1 declared in your component,
还要确保您在组件中声明了 form1,
form1 : string ;