在Angular中使用反应形式感动和有效 [英] touched and valid using reactive forms in Angular
问题描述
我该如何使用角度4中的反应形式使用接触和有效的属性.我已经在模板驱动的形式中使用了,您可以将此<span class="text-muted" *ngIf="!fname.valid && fname.touched"> Please enter a valid first name</span>
放在输入字段下方.我还了解到,由于您必须在component.ts中编写逻辑,因此反应形式会更好.因此,我希望它以反应形式实现,并且我坚持如何使用感动和有效的属性.
How can i use the touched and valid properties using reactive forms in angular 4. I've used in template driven forms and you can just put this <span class="text-muted" *ngIf="!fname.valid && fname.touched"> Please enter a valid first name</span>
below the input field. I've also learned that reactive forms would be better since you have to write the logic in the component.ts. So i want it to implement in the reactive form and i'm stuck on how to use the touched and valid properties.
html
html
<form [formGroup]="form" (ngSubmit)="onSignIn(form)">
<div class="form-group">
<input type="text" class="form-control" id="email" placeholder="Enter email" formControlName="email">
</div>
<div class="form-group">
<input type="password" class="form-control" id="password" placeholder="Password" formControlName="password">
</div><button class="btn btn-primary btn-block" type="submit" [disabled]="!form.valid">Sign In</button>
</form>
ts
ngOnInit() {
this.form = this.formBuilder.group({
email: [null, [Validators.required, Validators.email]],
password: [null, Validators.required],
});
}
onSignIn(form: FormGroup){
const email = form.value.email;
const password = form.value.password;
this.authService.loginUser(email, password)
.subscribe(
data => {
this.router.navigate(['/settings']);
alert("Login Successful");
console.log(data);
},
error => {
alert("Invalid Email or Password");
console.log(error);
});
}
推荐答案
尝试一下
<span class="text-muted" *ngIf="!form.controls['email'].valid && form.controls['email']?.touched"> Please enter a valid first name</span>
这篇关于在Angular中使用反应形式感动和有效的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!