search

Home  >  Q&A  >  body text

No need to subscribe to Observable, an imperative way to edit reactive form data in Angular

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粉587970021P粉587970021318 days ago410

reply all(1)I'll reply

  • P粉604848588

    P粉6048485882024-03-30 17:28:22

    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

    reply
    0
  • Cancelreply