如何在Angular 4中使用TypeScript设置文本框值?我的尝试无效
解决Angular 4中TypeScript设置文本框值失败的问题
我看了你的代码,问题主要出在三个地方,咱们一步步来修正:
1. 组件未声明绑定变量,且函数赋值语法错误
你在HTML里试图绑定setTextBoxValue,但组件类里根本没声明这个变量;而且clickMe函数里的赋值写法也不对,Angular组件里要访问类属性得用this关键字。
修正后的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'; // 先声明要绑定的变量,初始化可以为空字符串 setTextBoxValue: string = ''; clickMe() { // 使用this访问类的属性并赋值 this.setTextBoxValue = "new value"; } }
2. HTML中双向绑定与value属性冲突
你同时用了[(ngModel)]="form1"和value="{{setTextBoxValue}}",这两个是冲突的——双向绑定ngModel会完全接管输入框的值,value属性的设置会被忽略。咱们只需要把ngModel绑定到setTextBoxValue就行。
修正后的app.component.html:
<form class="example-form"> <mat-form-field class="example-full-width"> <!-- 只保留ngModel绑定到咱们声明的变量 --> <input matInput class='aaaa' placeholder="Favorite food" [(ngModel)]="setTextBoxValue" name="food"> </mat-form-field> <button (click)='clickMe()'>Click Me</button> </form>
注意:使用
ngModel的时候必须给输入框加name属性,否则Angular会报错哦。
这样修改之后,点击按钮就能成功把文本框的值设置为"new value"了。
内容的提问来源于stack exchange,提问作者JanithCW
相关产品推荐
相关产品推荐

