Angular 4 Reactive Form Validator Required 在预设值时显示触摸错误

Angular 4 Reactive Form Validator Required shows error on touch when value is preset

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

<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.nameValuethis.editTeamFormGroup 创建之前设置

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

模板

<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 ]
      });
    });
}