有几个问题:
1-模型未在任何地方定义。因此,模型。用户名无效。只需在您的Cals中的某个地方使用用户名或定义模型即可。
2-如果不打算在模板中使用变量(#username=“ngModel”),则不需要这些变量。例如,您可以执行以下操作:
<input #myUsernameInput="ngModel">
{{ myUsernameInput.valid }} // true/false
{{ myUsernameInput.value }} the value
以及其他各种检查。但是您没有在任何地方执行这些检查,因此不需要定义变量。
3-不应在类中定义myForm,因为formGroups用于被动表单,而不是模板驱动的表单。如果要将值传递给方法,一种简单的方法如下:
<form (submit)="loginUser(username, password)">
<div class="form-group">
<label for="username">Username</label>
<input type="text" id="username" name="username"
[(ngModel)]="username" class="form-control" required>
<label for="password">Password</label>
<input type="password" id="password" name="password"
[(ngModel)]="password" class="form-control" required>
<div style="padding-top:20px">
<button type=submit class="button">Login</button>
</div>
</div>
</form>
import { Component, OnInit } from '@angular/core';
import { Router } from '@angular/router';
import { NgForm, FormControl, FormGroup, ReactiveFormsModule } from '@angular/forms'
@Component({
selector: 'app-login',
templateUrl: './login.component.html',
styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
constructor(private router: Router) {
}
ngOnInit() {
}
loginUser(username: string, password: string) {
if (username === "admin" && password === "admin"){
this.router.navigate(['mockup']);
}
}
}
解释模板驱动表单的最简单方法是,所有工作(意味着表单的构建、验证等)都在模板(html)中进行。这是有限的,因为你不能用反应驱动的表单做所有你能做的事情。然而,被动驱动的表单要复杂一些。选择哪一种取决于情况和偏好,但在这种情况下,模板驱动的表单完全可以使用。我建议你阅读这本指南,它非常有用。
https://angular.io/guide/forms