Search code examples
angularangular-forms

pre populate input in form angular


I have a component with a form that has some inputs with data validations How can I pre populate with the logged user's info?

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> 

... and so on for every field


Solution

  • When initializing your form with this.fb.group you can pass default data to your form inputs :

    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]],
          ...
        })
    

    If you want to update theses data after the initialization of the form, you can use the patchValue method :

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