在表单 angular 中预填充输入

pre populate input in form angular

我有一个带有表单的组件,其中包含一些带数据验证的输入 我如何预先填充已登录用户的信息?

userService.ts

public getCurrentUser():User {
  return this.currentUser;
}

component.ts

vendorInformationForm: FormGroup;
states = states;

constructor(
  private fb: FormBuilder,
  private userService: UserService) { }

ngOnInit() {
  this.initForm();
}

initForm() {
  this.vendorInformationForm = this.fb.group({
    name: [null],
    adress: ['', [Validators.required, Validators.maxLength(60)]],
    city: ['', Validators.maxLength(20)],
    state: ['', [Validators.required]],
    zip: ['', [Validators.required]],
    vendorNumber: [null],
    minimumOrderAmount: ['', [Validators.required, Validators.min(0) ,Validators.pattern('^[0-9]$')]],
    freightPrepaidAt: ['', [Validators.required]],
    preferredShipper: ['', [Validators.required]],
    email: ['', [Validators.required, Validators.email]]
  })
}

component.html

<div class="form-row">
    <div class="col-12">
        <div class="form-group">
            <label for="adress">Adress</label>
            <input type="text" id="adress" class="form-control" formControllName="adress"> 
        </div>
    </div>
</div> 

...每个字段依此类推

使用 this.fb.group 初始化表单时,您可以将默认数据传递给表单输入:

User user = this.getUser()
    this.vendorInformationForm = this.fb.group({
      name: [this.user.name ? this.user.name : ''],
      adress: [this.user.address ? this.user.address : '', [Validators.required, Validators.maxLength(60)]],
      email: [this.user.email ? this.user.email : '', [Validators.required, Validators.email]],
      ...
    })

如果要在表单初始化后更新这些数据,可以使用patchValue方法:

this.vendorInformationForm.patchValue('yourinputname', 'thenewvalue')

您可以使用

this.form.setValue({
  name: [response.name],
  adress: [response.address]
});

根据您的回复进行相应替换

我们可以使用setValue()patchValue()来设置数据

这样试试:

let vendorData = {
   name : "Adrita",
   ...
}

this.vendorInformationForm.patchValue(vendorData)

如果您拥有所有信息,则使用 setValue 否则使用 patchValue

用户有什么属性?通常,您可以使用表单组 patchValuesetValue 函数

this.vendorInformationForm.patchValue(this.userService.getCurrentUser());

this.vendorInformationForm.setValue(this.userService.getCurrentUser());

patchValue 修补值和表单配置之间匹配的所有字段。 setValue 函数要求数据完全是 formgroups 形式。

要更新表单,您可以使用方法 patchValue() 或 setValue() 来完成。这样:

component.ts

   const userInfo =  this.userService.getCurrentUser();

   this.vendorInformationForm.patchValue(userInfo);