Reputation: 175
How to set text box value in Angular 4 using TypeScript? I tried in this way but it doesn't work.
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";
}
}
Upvotes: 1
Views: 26564
Reputation: 3443
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:
<input matInput placeholder="Input" [(ngModel)]="inputVar">
In the component (.ts
) you could have:
constructor() { this.inputVar = "initial value" }
And then a button with (click)
event like you have:
<button type="button" (click)="changeInputVar()">Test Change</button>
And again in your .ts
you have the changeInputVar()
defined:
private changeInputVar(): void {
this.inputVar = "changed";
}
Here is a demo.
Upvotes: 10
Reputation: 222522
just set the model value inside the function,
this.fomr1 = "new value";
also make sure you have the form1 declared in your component,
form1 : string ;
Upvotes: 0