我在Angular 7中完成了表单,并且我做了*ngIf
条条件来告诉用户,他没有将所有数据插入表单。尝试在!
之前使用*ngIf
,对于Visual Studio Code来说还可以,但是效果相反。
这是错误:
[角度]标识符“名称”未定义。 '__type'不包含RegisterComponent的成员属性messageForm
HTML文件:
<h1>Log in</h1>
<form [formGroup]="messageForm" (ngSubmit)="onSubmit()">
<h5 *ngIf="success">Your form is valid!</h5>
<label>
Tvoj nick:
<input type="text" formControlName="name">
<div *ngIf="submitted && messageForm.controls.name.errors" class="error">
<div *ngIf="messageForm.controls.name.errors.required">... aale no, tvoj nick potrebujeme, aby si mal svoj tim</div>
</div>
</label>
<label>
Email:
<input type="email" formControlName="email">
<div *ngIf="submitted && messageForm.controls.email.errors" class="error">
<div *ngIf="messageForm.controls.email.errors.required">Email je dolezity na zasielanie informacii pre teba</div>
</div>
</label>
<label>
Tvoje heslo:
<input type="password" formControlName="password">
<div *ngIf="submitted && messageForm.controls.password.errors" class="error">
<div *ngIf="messageForm.controls.password.errors.required">Heslo je zaklad registracie!</div>
</div>
</label>
<input type="submit" value="Zaregistruj sa" class="cta">
</form>
TS文件:
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
@Component({
selector: 'app-register',
templateUrl: './register.component.html',
styleUrls: ['./register.component.scss']
})
export class RegisterComponent implements OnInit {
messageForm: FormGroup;
submitted = false;
success = false;
constructor(private formBuilder: FormBuilder) { }
ngOnInit() {
this.messageForm = this.formBuilder.group({
name: ['', Validators.required],
email: ['', Validators.required],
password: ['', Validators.required]
});
}
onSubmit(){
this.submitted = true;
if(this.messageForm.invalid){
return;
}
this.success = true;
}
}
答案 0 :(得分:1)
尝试以这种方式设置验证
<div *ngIf="submitted && f.name.errors" class="invalid-feedback">
<div *ngIf="f.name.errors.required">Name is required</div>
</div>
在.ts
文件中
get f() { return this.messageForm.controls; }
更新
<div *ngIf="name?.errors.required">Name is required.</div>
this.messageForm = this.formBuilder.group({
email: ['', [Validators.required, Validators.email]],
password: ['', [Validators.required, Validators.minLength(3)]]
});
更新电子邮件验证问题
<div *ngIf="submitted && f.email.errors" class="invalid-feedback">
<div *ngIf="f.email.errors.required">Email is required</div>
<div *ngIf="f.email.errors.email">Email must be a valid email address</div>
</div>