为反应式表单初始化输入字段并使控件有效的正确方法

Correct way to initialize input fields for reactive forms & have the control valid

这里的问题应该很简单,但我无法为反应式表单初始化输入字段并使该控件有效。

假设我有这个代码:

@Component({
  selector: 'app-profile-editor',
  templateUrl: './profile-editor.component.html',
  styleUrls: ['./profile-editor.component.css']
})
export class ProfileEditorComponent {
  profileForm = this.fb.group({
    firstName: string,
    lastName: string,

    address: this.fb.group({
      fName: ['initial value', [Validators.required]],
      city: ['', [Validators.required]],
      state: [''],
      zip: ['']
    }),
  });

  constructor(private fb: FormBuilder) { }
}

在我的模板中可以说:

<input [(ngModel)]="firstName" formControlName="fName" />

问题是这样设置默认值是行不通的:

fName: ['initial value', [Validators.required]],

第二种方式无效:

fName: new FormControl('initial value', [Validators.required])

第三种方法是在模板中这样做也不起作用:

 <div>
    <input [(ngModel)]="firstName" formControlName="fName" [value]="'default value'"/>
 </div>

第四种方法是:

this.address.controls['fName'].setvalue('default value');
this.address.controls['fName'].updateValueAndValidity();

因此,当我尝试所有这些组合或一次尝试其中之一,并进入调试器并验证以下值是什么时:this.address.controls['fName'].value 它给了我空值 --> ''

因此,即使在我的表单中最初填充了该字段并且我必须提供其他字段然后由于该字段我的表单无效我然后它没有显示我的保存按钮已启用。

有人可以解释为什么会出现这种行为,或者解释一下正确的处理方式是什么吗?

注意:我只是在这里给出一个小代码示例作为提示,因为我的真实代码是更大的专有 angular6 应用程序的一部分。

我必须清理这个例子,但这里有一个使用:

https://stackblitz.com/edit/angular-reactive-forms-jhg6ds?file=app%2Fapp.component.ts

(稍后会更新此示例。)

在这种情况下,没有显示默认值,因为我认为这是与 ngModel 内容的并发,所以我想在 ngModel 的内容为空时设置默认值事件(创建空表单时的示例,用户必须找到一些已经填写的字段(然后有效))

编辑版本:https://stackblitz.com/edit/angular-reactive-forms-atvaym

模板:

<form [formGroup]="SignupForm" (ngSubmit)="onSubmit()">
    <div class="form-group">
        <label for="username">UserName</label>
        <input type="text" class="form-control" id="username" formControlName="username">
        <span class="help-block" *ngIf="!SignupForm.controls.username.valid && SignupForm['controls'].username.touched">
   <span *ngIf="SignupForm['controls'].username.hasError('nameIsForbidden')">name is invalid</span>
        <span *ngIf="SignupForm['controls'].username.hasError('required')">field is required</span>
        </span>
    </div>

    <div class="form-group">
        <label for="email">Email</label>
        <input type="email" class="form-control" id="email" formControlName="email">
        <span class="help-block" *ngIf="!SignupForm.controls.email.valid && SignupForm['controls'].email.touched">
   <span *ngIf="SignupForm['controls'].email.hasError('emailIsForbidden')">name is invalid</span>
        <span *ngIf="SignupForm['controls'].email.hasError('required')">field is required</span>
        </span>
    </div>

    <div class="radio" *ngFor="let gender of genders">
        <label>
<input type="radio" [value]="gender" formControlName = "gender">{{gender}}
</label>
    </div>

    <div formArrayName="hobbies">
        <h4>Hobbies</h4>
        <button class="btn btn-default" type="button" (click)="onAddHobby()">Add Hobby</button>
        <div class="form-group" *ngFor="let hobbyControl of SignupForm['controls'].hobbies['controls']; let i=index">
            <div [formGroupName]="i">
                <div [formGroup]="SignupForm['controls'].hobbies['controls'][i]">
                    <input type="text" class="form-control" formControlName="name">
                </div>
            </div>
        </div>
    </div>
    <span class="help-block" *ngIf="!SignupForm.valid && SignupForm.touched">please enter valid data</span>
    <button class="btn btn-primary" type="submit">Submit</button>
</form>

打字稿:

  ngOnInit(){
    this.SignupForm = this.fb.group({
      username: [{value: 'default name', disabled: false}, [Validators.required, this.validateName()]],
      email: [{value: 'default name', disabled: false}, [Validators.required, Validators.email, this.validateEmail()]],
      gender: [{value: 'female', disabled: false}, [Validators.required]],
      hobbies: this.fb.array([])
    });
  }

  onAddHobby(){
    const controls = <FormArray>this.SignupForm.controls['hobbies'];
    let control = this.fb.group({
      name: [{value: 'hobbi', disabled: false}]
    });
    
    controls.push(control);
  }

  private validateName(): ValidatorFn {
    return (control: AbstractControl): {[key: string]: any} => {
      for(let i of this.forbiddenUserNames){
        if(i === control.value){
          return {'nameIsForbidden': true};
        } else {
          return null;
        }
      }
    }
  }
    
  private validateEmail(): ValidatorFn {
    return (control: AbstractControl): {[key: string]: any} => {
      if(control.value === 'test@test.com'){
        return {'emailIsForbidden': true};
      } else {
        return null;
      }
    }
  }

而且我建议看看这篇关于异步验证器的文章 https://alligator.io/angular/async-validators/