网站搜索

html - 如何在 Angular 4 中使用 TypeScript 设置文本框的值?


如何在 Angular 4 中使用 TypeScript 设置文本框的值?我尝试了这种方法,但它不起作用。

app.component.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

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";
   }
}

答案#1

移除 value="{{setTextBoxValue}}" 并仅使用 [(ngModel)]。例如,如果你的组件(.ts)中有 private inputVar: string;,那么元素将如下所示:

<input matInput placeholder="Input" [(ngModel)]="inputVar">

在组件 (.ts) 中,您可以有:

constructor() { this.inputVar = "initial value" }

然后是一个带有 (click) 事件的按钮,就像你有的那样:

<button type="button" (click)="changeInputVar()">Test Change</button>

在你的 .ts 文件中,你再次定义了 changeInputVar():

private changeInputVar(): void {
  this.inputVar = "changed";
}

这是一个演示。

答案#2

只需在函数内部设置模型值,

this.fomr1 = "new value";

还要确保你在组件中声明了 form1,

form1 : string ;