我正在尝试在表单提交时使用admin验证用户名和密码。 当我尝试从用户名字段获取用户插入的值时,它显示此错误。
这是我的html代码文件:- second-page.component.html
<div class="row justify-content-center mt-5">
<div class="card shadow p-3 mb-5 bg-white rounded w-25" style="width: 18rem;">
<div class="card-body">
<div>
<h4 class="text-center">Login Form</h4>
</div>
<div class="mt-4">
<form novalidate #loginForm="ngForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<label for="userName">User Name</label>
<input required ngModel name="userName" #userName="ngModel" (change)="log(userName)" id="userName" type="text" class="form-control">
<div class="alert alert-danger" *ngIf="userName.touched && !userName.valid">
<div *ngIf="userName.errors.required">User Name is required.</div>
</div>
</div>
<div class="form-group">
<label for="password">Password</label>
<input required ngModel name="password" #password="ngModel" (change)="log(password)" id="password" type="password" class="form-control">
<div class="alert alert-danger" *ngIf="password.touched && !password.valid">
<div *ngIf="password.errors.required">Password is required.</div>
</div>
</div>
<div class="form-group text-center">
<input class="btn btn-outline-secondary mr-2" type="reset" id="button" value="Clear">
<button class="btn btn-primary" type="submit" [disabled]="loginForm.invalid">Submit</button>
</div>
</form>
</div>
</div>
</div>
</div>
这是我的打字稿代码文件: second-page.component.ts
import { Component, OnInit } from '@angular/core';
import { FormControl, FormGroup } from "@angular/forms";
import { Router } from "@angular/router";
@Component({
selector: 'app-second-page',
templateUrl: './second-page.component.html',
styleUrls: ['./second-page.component.css']
})
export class SecondPageComponent implements OnInit {
loginForm: FormGroup;
constructor(private router: Router) { }
ngOnInit() {
}
log(x){ console.log(x); }
onSubmit()
{
console.log("Hello");
let username = this.loginForm.get('UserName').value;
let password = this.loginForm.get('Password').value;
if (username === 'admin' && password === 'admin')
{
this.router.navigate(['/registrationpage']);
}
}
}
答案 0 :(得分:1)
由于您使用的是模板驱动的表单,并且您试图在控制器端使用formControl来获取价值,因此基本上您将两者混在一起。
在您的情况下(模板驱动的表单),您需要像这样使用viewChild(局部变量)来获取表单-
@ViewChild('loginForm') loginForm: any;
然后您可以使用-
添加验证或获取价值this.loginForm.valid // or whatever you need to play with form
有关更多详细信息-
答案 1 :(得分:1)
如前所述,您正在将反应形式与模板驱动混合。
如果只需要访问表单值,则可以将表单的值传递给submit
函数:
<form novalidate #loginForm="ngForm" (ngSubmit)="onSubmit(loginForm.value)">
然后,您可以在函数中访问这些表单值,例如:
onSubmit(formValue) {
if (formValue.userName === "admin" && formValue.password === "admin") {
console.log('admin')
} else {
console.log('not admin!')
}
}
答案 2 :(得分:0)
您必须初始化FormGroup。
this.loginForm = {
"UserName" : new FormControl({value: ''}, Validators.required),
"Password" : new FormControl({value:''},Validators.required)
}