1

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";
   }
}
4
  • change your [(ngModel)] value make it to setTextBoxValue so that you can get you result or form1 : string ; this.form1 = "your value"; Commented Jan 5, 2018 at 13:49
  • Thanks for the reply. but it doesnt work either. Commented Jan 5, 2018 at 13:56
  • try luck by adding <input type="text" matInput class='aaaa' placeholder="Favorite food" [(ngModel)]="form1" "> Commented Jan 5, 2018 at 14:03
  • Try using either [(ngModel)] or {{setTextBoxValue}}, if it works I would be interested to know why it works. Commented Jan 5, 2018 at 14:03

2 Answers 2

10

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.

Sign up to request clarification or add additional context in comments.

Comments

0

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 ;

1 Comment

I tried! But it doesn't work. But it gives no errors.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.