我正在尝试按照教程在我的表单中实现角度验证器,但忽略了验证。这是我的代码:
查看
<div class="form-group row">
<label for="inputLocalita" class="col-sm-2 col-form-label col-form-label-sm">Località</label>
<label *ngIf="!edit" class="col-sm-10 col-form-label col-form-label-sm grey" id="inputLocalita">{{immobile.localita}}</label>
<div *ngIf="edit" class="col-sm-10">
<input type="text" class="form-control form-control-sm" id="inputLocalita" formControlName="localita" placeholder="Località">
</div>
<div *ngIf="imm.controls.localita.errors && (imm.controls.localita.dirty || imm.controls.localita.touched)">
<p *ngIf="imm.controls.localita.errors.required">Field is required</p>
<p *ngIf="imm.controls.localita.errors.minlength">Field must be 8 characters long</p>
</div>
</div>
控制器
ngOnInit() {
this.imm = new FormGroup({
comune: new FormControl(),
provincia: new FormControl(),
comuneObj: new FormControl(),
cap: new FormControl(),
indirizzo: new FormControl(),
civico: new FormControl(),
localita: new FormControl([
Validators.minLength(4),
Validators.required]),
destinazioneUso: new FormControl(),
destinazioneUsoAltro: new FormControl(),
destinazioneUsoPrincipale: new FormControl(),
destinazioneUsoSecondaria: new FormControl(),
});
我错过了什么吗?谢谢你的提示。
答案 0 :(得分:0)
你正在弄乱formControl
的使用。在创建自定义FormControl
时,请使用以下语法(请参阅FormControl的 API ):
// for single validator
customControl = new FormControl('value', Validators.maxLength(5));
// for multiple validators(with Validators.compose)
customControl = new FormControl('value', Validators.compose([Validators.minLength(4), Validators.required]));
// or(without Validators.compose)
customControl = new FormControl('value', Validators.compose([Validators.minLength(4), Validators.required]));
将formGroup代码更改为以下任一方式将解决您的问题:
选项1:在不使用new FormControl()
this.imm = new FormGroup({
comune: [],
provincia: [],
comuneObj: [],
cap: [],
indirizzo: [],
civico: [],
localita: ['', Validators.compose([Validators.minLength(4), Validators.required])],
destinazioneUso: [],
destinazioneUsoAltro: [],
destinazioneUsoPrincipale: [],
destinazioneUsoSecondaria: [],
});
选项2:更正formControl部件语法。
this.imm = new FormGroup({
comune: new FormControl(),
provincia: new FormControl(),
comuneObj: new FormControl(),
cap: new FormControl(),
indirizzo: new FormControl(),
civico: new FormControl(),
localita: new FormControl('', Validators.compose([Validators.minLength(4), Validators.required])),
destinazioneUso: new FormControl(),
destinazioneUsoAltro: new FormControl(),
destinazioneUsoPrincipale: new FormControl(),
destinazioneUsoSecondaria: new FormControl(),
});