我正在尝试设计一个登录表单。我采用的模型中的两个属性,在 html 文件中的用户名和密码输入字段中使用了两种方式绑定,并尝试匹配用户给出的输入,以根据我在组件文件中编写的一些硬编码用户名/密码进行身份验证。但不确定为什么我会收到错误:
Failed to compile.
src/app/login/login.component.html:10:102 - error TS2322: Type 'Event' is not assignable to type 'string'.
10 <input type="text" class="form-control" name="username" [(ngModel)]="login.userName" #username="ngModel" required>
~~~~~~~~~~~~~~~~~~~~~
src/app/login/login.component.ts:7:16
7 templateUrl: './login.component.html',
~~~~~~~~~~~~~~~~~~~~~~~~
Error occurs in the template of component LoginComponent.
Run Code Online (Sandbox Code Playgroud)
有人可以帮忙吗!
登录.组件.ts
import { Component, OnInit } from '@angular/core';
import {Router} from '@angular/router';
import {Login} from './login.model';
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ["./login.component.css","../app.component.css"]
})
export class LoginComponent implements OnInit {
login=new Login();
constructor(private _router: Router) { }
users: any[]=[
{
userName: "admin",
password: "admin"
},
{
userName: "user1",
password: "user1@123"
},
{
userName: "user2",
password: "user2@123"
}
];
IsAuthorized=false;
Clickedlogin(){
const name=this.login.userName;
const password=this.login.password;
const user = this.users.filter(currUser => currUser.userName === name && currUser.password === password)[0];
if (user) {
this.IsAuthorized=true;
this._router.navigate(['/book-ride']);
}
else {
this.IsAuthorized=false;
this._router.navigate(['/login']);
}
}
ngOnInit(): void {
}
}
Run Code Online (Sandbox Code Playgroud)
登录.component.html
<form id="loginform" class="form-horizontal" role="form">
<div style="margin-bottom: 25px" class="input-group">
User Name
<input type="text" class="form-control" name="username"
[(ngModel)]="login.userName" #username="ngModel" required>
</div>
<div style="margin-bottom: 25px" class="input-group">
Password
<input type="password" class="form-control" name="password"
#password="ngModel" [(ngModel)]="login.password" required>
</div>
<div style="margin-top:10px" class="form-group">
<div class="col-sm-12 controls">
<button (click)="Clickedlogin()" class="btn btn-primary">Login</button>
</div>
</div>
</form>
Run Code Online (Sandbox Code Playgroud)
登录.model.ts
export class Login {
public userName: string="";
public password: string="";
}
Run Code Online (Sandbox Code Playgroud)
有一次我忘记在我的模块中导入 FormsModule,并且出现了同样的错误
/* src/app/app.module.ts */
import { FormsModule } from '@angular/forms';
...
@NgModule({
imports: [
FormsModule,
...
],
...
})
export class AppModule { }
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
5297 次 |
| 最近记录: |