如何将文本从输入保存到角度变量?

时间:2018-04-29 03:42:30

标签: html angular

我正在尝试从我的一个component.html文件中获取文本,并将输入保存到我的.ts文件中的方法中的变量中。你能帮忙吗?

home.component.html文件:

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

home.component.ts文件:

export class HomeComponent implements OnInit {

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

    }

}

2 个答案:

答案 0 :(得分:0)

如果你使用角度,它应该是

ngModel 而不是 ng-model

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

并在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);
    }

}

答案 1 :(得分:0)

您需要将ng-model更改为ngModel

  

ng-model : - angularjs

     

ngModel : - Angular 2或更高

<强> HTML

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

组件

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);
 }
}