Chris Dunn
Chris Dunn

Reputation: 21

How to save text from input to variable in angular?

I'm trying to take text from one of my component.html files and save the input to a variable in a method in one of my .ts files. Can you help?

home.component.html file:

Username: <input ng-model="username"><br>
Password: <input ng-model="pass">  
<button (click)="login()">Login</button>

home.component.ts file:

export class HomeComponent implements OnInit {

    login()
    {
     const usr= {{username}};
     const password={{pass}};
     print("user is"+usr " Password is"+password);

    }

}

Upvotes: 0

Views: 14239

Answers (2)

Sharma Vikram
Sharma Vikram

Reputation: 2470

you need to change ng-model to ngModel

ng-model :- angularjs

ngModel :- Angular 2 or greater

Html

Username: <input [(ngModel)]="username"><br>
Password: <input [(ngModel)]="pass">  
<button (click)="login()">Login</button>

Component

export class HomeComponent implements OnInit {
 public username: String;
 public pass: String;
 public function login() {
 console.log('User Name: ' + this.username);
 console.log('Password: ' + this.pass);
 }
}

Upvotes: 0

Sajeetharan
Sajeetharan

Reputation: 222532

If you are using angular it should be

ngModel instead of ng-model

Username: <input  [(ngModel)]="username"><br>
Password: <input  [(ngModel)]="pass">  

and in component.ts

export class HomeComponent implements OnInit {
    username : string;
    password : string;

    login()
    {
     const usr= this.username;
     const password= this.password;
     console.log("user is"+usr " Password is"+password);
    }

}

Upvotes: 1

Related Questions