问题描述
在严格模式下使用Angular时,出现了无法使用FormBuilder解决的错误。
该应用使用以下命令检查IP:
saisie.component.ts
的代码:
import { Component,OnInit } from '@angular/core';
import { FormGroup,Validators,FormBuilder } from '@angular/forms';
@Component({
selector: 'app-saisie',templateUrl: './saisie.component.html',styleUrls: ['./saisie.component.scss']
})
export class SaisieComponent implements OnInit {
ipForm!: FormGroup;
isSubmitted = false;
constructor(private fb: FormBuilder) { }
ngOnInit(): void {
this.ipForm = this.fb.group({
ip: ["",Validators.required,Validators.pattern('(?:(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)\\.){3}(?:25[0-5]|2[0-4][0-9]|[01]?[0-9][0-9]?)')]
});
}
get f() { return this.ipForm.controls; }
onSubmit() {
this.isSubmitted = true;
console.log("ip :" + this.ipForm.value.login);
if (this.ipForm.invalid) {
console.log("vide");
return;
}
alert('JSon :\n ' + JSON.stringify(this.ipForm.value,null));
}
onReset() {
this.isSubmitted = false;
this.ipForm.reset();
}
}
对于saisie.component.html
:
<form [formGroup]="identForm" (ngSubmit)="onSubmit()">
<div class="field">
<label class="label">IPv4 :</label>
<div class="control">
<input type="text" formControlName="ip" class="form-control"
[ngClass]="{ 'is-invalid': submitted && f.ip.errors }" placeholder="n.n.n.n" />
<div *ngIf="submitted && f.ip.errors" class="invalid-Feedback">
<div *ngIf="f.ip.errors.required">Une IP valide est requise !</div>
</div>
</div>
</div>
<div class="field is-grouped">
<div class="control">
<button class="button is-link">Soumettre</button>
</div>
</div>
</form>
严格模式需要ipForm! = FormGroup
语句,但意味着未初始化。
我当然可以在模板中放置*ngIf
,但是在这种情况下,表单不会出现。
我做了各种形式的初始化,但是都没有用。感谢您的提前帮助!
解决方法
暂无找到可以解决该程序问题的有效方法,小编努力寻找整理中!
如果你已经找到好的解决方法,欢迎将解决方案带上本链接一起发送给小编。
小编邮箱:dio#foxmail.com (将#修改为@)