gpt4 book ai didi

预设值时,Angular 4 响应式(Reactive)表单验证器要求显示触摸错误

转载 作者:行者123 更新时间:2023-12-02 20:42:18 24 4
gpt4 key购买 nike

我遇到的问题是表单显示输入字段错误。我不知道为什么会出现这种情况,可能是由于缺乏理解。所以我有一个叫做编辑团队的组件。在这个编辑团队组件中,我有一个输入字段,其值设置为当前团队名称。如果我将焦点放在输入文本字段上,然后移除焦点以说明背景,那么即使预设值且未更改,表单也会触发“必需”错误。

<div class="form-group">
<label class="control-label" for="name">Name</label>
<input tabindex="0" type="text" placeholder="Please enter the team name" title="Please enter the team name" required value=""
id="name" class="form-control" name="name" formControlName="name" [value]="nameValue">

// This is the condition for when the error is shown.
// So when the input field is touched, check if an error
// exists for the validator required.
<div class='form-text error' *ngIf="editTeamFormGroup.controls.name.touched">
<div *ngIf="editTeamFormGroup.controls.name.hasError('required')" class="help-block error small">Team name is required.</div>
</div>
</div>

这是组件的构造函数和 ngOnIt 方法。订阅是针对团队服务内的可观察对象,当团队发生变化时,值也会发生变化。

constructor(private fb: FormBuilder,
private teamService: TeamService,
private router: Router,
public modalService: ModalService) { }

ngOnInit() {
this.teamService.teamChange.subscribe(result => {
this.team = result;
this.nameValue = this.team.name;
this.descriptionValue = this.team.description;
});


this.editTeamFormGroup = this.fb.group({
'name': [ this.nameValue, Validators.required ],
'description': [ this.descriptionValue, Validators.required ]
});
}

注意:控制台中没有错误。如果我将字符添加到预设值并将焦点更改到另一个元素,验证将按预期进行。

最佳答案

这是因为您设置表单的方式。如this.teamService.teamChange是异步的,你不能保证this.nameValue设置之前 this.editTeamFormGroup被 build 。

如果您等到获得必要的信息后再启动表单组,事情就会正常进行。并且不要使用 [value]formControlName 一起在<input>除非你有充分的理由。

模板

<form [formGroup]="editTeamFormGroup" *ngIf="editTeamFormGroup">
...
<div class="form-group">
<label class="control-label" for="name">Name</label>
<input tabindex="0" type="text" placeholder="Please enter the team name" title="Please enter the team name" required value=""
id="name" class="form-control" name="name" formControlName="name">

</form>

隐藏代码

ngOnInit() {
this.teamService.teamChange.subscribe(result => {
this.team = result;
this.nameValue = this.team.name;
this.descriptionValue = this.team.description;

this.editTeamFormGroup = this.fb.group({
'name': [ this.nameValue, Validators.required ],
'description': [ this.descriptionValue, Validators.required ]
});
});
}

关于预设值时,Angular 4 响应式(Reactive)表单验证器要求显示触摸错误,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/45726072/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com