Jan*_*hCW 1 html textbox typescript angular
如何使用TypeScript在Angular 4中设置文本框值?我以这种方式尝试过,但是没有用。
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>
Run Code Online (Sandbox Code Playgroud)
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";
}
}
Run Code Online (Sandbox Code Playgroud)
删除value="{{setTextBoxValue}}"并使用[(ngModel)]。例如,如果您private inputVar: string;在组件(.ts)中,则该元素将如下所示:
<input matInput placeholder="Input" [(ngModel)]="inputVar">
Run Code Online (Sandbox Code Playgroud)
在组件(.ts)中,您可以:
constructor() { this.inputVar = "initial value" }
Run Code Online (Sandbox Code Playgroud)
然后是一个具有(click)事件的按钮,例如:
<button type="button" (click)="changeInputVar()">Test Change</button>
Run Code Online (Sandbox Code Playgroud)
再次,您.ts已经changeInputVar()定义了:
private changeInputVar(): void {
this.inputVar = "changed";
}
Run Code Online (Sandbox Code Playgroud)
这是一个演示。
| 归档时间: |
|
| 查看次数: |
12761 次 |
| 最近记录: |