No need to subscribe to Observable, an imperative way to edit reactive form data in Angular
P粉587970021
P粉587970021 2024-03-29 18:37:15
0
1
386

Here's the process I've been using to subscribe and update a reactive form based on observable data.

Maybe there is a way to solve the problem without subscribing to the observable and changing the value.

@Component({
  selector: 'app-my-component',
  template: `
    <form [formGroup]="myForm">
      <input formControlName="name" />
      <input formControlName="email" />
    </form>
  `,
})
export class MyComponent implements OnInit {
  myForm: FormGroup;

  constructor(private fb: FormBuilder, private ds: DataService) {}

  ngOnInit() {
    this.myForm = this.fb.group({
      name: '',
      email: '',
    });

    ds.data$.subscribe((data) => {
      this.myForm.setValue({
        name: data.name,
        email: data.email,
      });
    });
  }


}

P粉587970021
P粉587970021

reply all(1)
P粉604848588

Typically, one way to eliminate subscriptions is to use an asynchronous pipe in a wrapper

@Component({
  template: `<app-user-form-component *ngIf="user$ | async as user"  [user]="user"/>`,
  // closed tag is a new feature of angular
  selector: 'app-update-user-form-container'
}) 
class UpdateUserFormContainer {
  user$ = inject(DataService).data$;
}

The form itself can handle user updates within NgOnInit or NgOnChanges (if there are likely to be multiple updates and setting the form values ​​is important in that case)

export class MyComponent implements OnInit {
  myForm = inject(NonNullableFormBuilder).group({
     name: '',
     email: '',
  }); // this way form is not just FormGroup but the type is inferred from fields
  // i.e. this.myForm.getRawValue() would return you {name: string, email: string};
  @Input({required: true}) user1: User; // required input is new feature of angular
  
  ngOnChanges(changes: SimpleChanges) {
    if('user' in changes) {
      this.myForm.setValue({
       name: this.user.name,
       email: this.user.email,
     })
    }
  }
}

Note: Some very cutting-edge Angular features are used in this example. You can follow the same pattern, but you don't necessarily need to use every feature

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template