Gri*_*rim 2 angular angular-reactive-forms
我遇到的问题是表单显示输入字段错误。我不知道它为什么显示,可能是由于缺乏理解。所以我有一个叫做编辑团队的组件。在这个编辑团队组件中,我有一个输入字段,其值设置为当前团队名称。如果我将焦点放在输入文本字段上,然后移除焦点以让我们说背景,那么即使值预设且未更改,表单也会触发“必需”错误。
<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>
Run Code Online (Sandbox Code Playgroud)
这是组件的构造函数和 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 ]
});
}
Run Code Online (Sandbox Code Playgroud)
注意:控制台中没有错误。如果我将字符添加到预设值并将焦点更改为另一个元素,则验证会按预期工作。
这是因为您设置表单的方式。由于this.teamService.teamChange是异步的,您不能保证在创建之前进行this.nameValue设置。 this.editTeamFormGroup
如果您等到获得必要的信息然后启动表单组,事情就会正常工作。除非有充分的理由,否则不要[value]与formControlNamein一起使用<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>
Run Code Online (Sandbox Code Playgroud)
背后的代码
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 ]
});
});
}
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
1943 次 |
| 最近记录: |