Jos*_*eph 10 angular angular-reactive-forms
如何使用角度4中的反应形式使用触摸和有效属性.我已经在模板驱动的表单中使用,您可以将它<span class="text-muted" *ngIf="!fname.valid && fname.touched"> Please enter a valid first name</span>
放在输入字段下面.我还了解到反应形式会更好,因为你必须在component.ts中编写逻辑.所以我希望它以反应形式实现,我坚持如何使用触摸和有效的属性.
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>
Run Code Online (Sandbox Code Playgroud)
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);
});
}
Run Code Online (Sandbox Code Playgroud)
尝试这个
<span class="text-muted" *ngIf="!form.controls['email'].valid && form.controls['email']?.touched"> Please enter a valid first name</span>
Run Code Online (Sandbox Code Playgroud)
您可以以类似的方式使用它。要获取 FormControl,请使用FormGroup 对象上的get方法,然后使用hasError:
// in your template
form.get('email').hasError('required') && form.get('email').touched
form.get('email').hasError('email') && form.get('email').touched
form.get('password').hasError('required') && form.get('password').touched
Run Code Online (Sandbox Code Playgroud)
您还可以在组件中为此创建一些不错的方法/getter。
<form [formGroup]="form" (ngSubmit)="onSignIn(form)">
<div class="form-group">
<input type="text" class="form-control" id="email" placeholder="Enter email" formControlName="email">
<span class="text-muted" *ngIf="form.get('email').hasError('required') && form.get('email').touched">Email is required</span>
</div>
<div class="form-group">
<input type="password" class="form-control" id="password" placeholder="Password" formControlName="password">
<span class="text-muted" *ngIf="form.get('password').hasError('required') && form.get('password').touched">Password is required</span>
</div><button class="btn btn-primary btn-block" type="submit" [disabled]="!form.valid">Sign In</button>
</form>
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
14173 次 |
最近记录: |