Gon*_*alo 1 typescript angular angular-reactive-forms angular5
大家好,
我正在努力为名称输入制作验证器,我只是从 angular wiki 回复了代码,但仍然无法正常工作。
你能帮我找出问题吗?
谢谢指教。
我的 HTML 代码:
<form [formGroup]="formAlta" (ngSubmit)="addRepresentacio()">
<div class="form-group">
<label for="namePro">Nom</label>
<input id="namePro" class="form-control" formControlName="namePro" placeholder="Nom del professional" required>
<div *ngIf="namePro.invalid && (namePro.dirty || namePro.touched)" class="alert alert-danger form-danger" role="alert">
<div *ngIf="namePro.errors.required">
El Nom del professional es obligatori
</div>
</div></form>
Run Code Online (Sandbox Code Playgroud)
还有我的 TS 组件
formAlta: FormGroup;
ngOnInit() {
this.formAlta = new FormGroup({
idPro: new FormControl(),
documentTypePro: new FormControl(),
namePro: new FormControl('',[Validators.required]),
rProfessional: new FormControl(this.tipusPro),
firstSurnamePro: new FormControl(),
secondSurnamePro: new FormControl(),
businessNamePro: new FormControl(),
idCli: new FormControl(),
documentTypeCli: new FormControl(),
nameCli: new FormControl('',Validators.required),
rClient: new FormControl(this.tipusCli),
firstSurnameCli: new FormControl(),
secondSurnameCli: new FormControl(),
businessNameCli: new FormControl(),
idPermis: new FormArray([]),
dateFiPermis: new FormArray([])
});
}
Run Code Online (Sandbox Code Playgroud)
您应该在您的 component.ts 中创建一个 getter 方法,如下所示以获取模板中的表单控件
get formAltaControls(): any {
return this.formAlta['controls'];
}
Run Code Online (Sandbox Code Playgroud)
在你的组件.html
<div *ngIf="formAltaControls.namePro.invalid && (formAltaControls.namePro.dirty || formAltaControls.namePro.touched)" class="alert alert-danger form-danger" role="alert">
<div *ngIf="formAltaControls.namePro.errors.required">
El Nom del professional es obligatori
</div>
Run Code Online (Sandbox Code Playgroud)