2

How can extract the data to pass it to the form?

user$!: Observable<UserI>

ngOnInit(): void {
  this.user$ = this.userService.getPerson();
  this.initializeForm();
}

initializeForm(): void {
  this.form = this.fb.group({
    fullName: new FormControl(?, Validators.required),
  });
}

1 Answer 1

2

You have multiple options:

You could initialize the form when the data is loaded or you could initialize the form with empty/default values and set update the values when the data is loaded.

Method 1:

ngOnInit(): void {
  this.userService.getPerson().pipe(
      tap(user => this.initializeForm(user))
  ).subscribe();
}

initializeForm(user: UserI): void {
  this.form = this.fb.group({
    fullName: new FormControl(user.fullName, Validators.required),
  });
}

Method 2:

ngOnInit(): void {
  this.initializeForm();
  this.userService.getPerson().pipe(
      tap(user => {
          this.form.get('fullName').setValue(user.FullName);
      })
  ).subscribe();
}

initializeForm(): void {
  this.form = this.fb.group({
    fullName: new FormControl('', Validators.required),
  });
}

Personally I prefer to create fields for my controls:

readonly fullName = new FormControl('', Validators.required);

ngOnInit(): void {
  this.initializeForm();
  this.userService.getPerson().pipe(
      tap(user => {
          this.fullName.setValue(user.FullName);
      })
  ).subscribe();
}

initializeForm(): void {
  this.form = this.fb.group({
    fullName: this.fullName,
  });
}

Then I can access them directly, including in html

<input [formControl]="fullName"/>
<span *ngIf="fullName.errors?.required">Fullname is required</span>
Sign up to request clarification or add additional context in comments.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.