Skip to content Skip to sidebar Skip to footer

How To Update A Reactive Form Field By Button Click On Different Component?

I have an application where my requirement is upon a button click (present in header component) the form field in another component will get updated. But the problem is the value i

Solution 1:

That isn't how the component interaction works in Angular. To share data among components, you could either use EventEmitter for related components or a singleton service for unrelated components.

Here is an illustration using a singleton service

share.service.ts

import { Injectable } from"@angular/core";

import { ReplaySubject } from"rxjs";

@Injectable()
exportclassShareService {
  public headerClickSrc = newReplaySubject<any>(1);
  public headerClick$ = this.headerClickSrc.asObservable();

  constructor() {}
}

header.component.ts

import { Component } from"@angular/core";
import { ShareService } from"../share.service";

@Component({
  selector: "app-header",
  templateUrl: "./header.component.html"
})
exportclassHeaderComponent {
  constructor(private share: ShareService) {}

  set() {
    this.share.headerClickSrc.next("fetched value");
  }
}

child.component.ts

exportclassChildComponent implements OnInit, OnDestroy {
  closed$ = newSubject<any>();
  constructor(private fb: FormBuilder, private share: ShareService) {}

  test = this.fb.group({
    sample: [""]
  });

  ngOnInit() {
    this.share.headerClick$.pipe(
      takeUntil(this.closed$)
    ).subscribe({
      next: value => {
        this.test.patchValue({
          sample: value
        });
        console.log(this.test.value);
      }
    });
  }

  ngOnDestroy() {
    this.closed$.next(); // <-- close open subscriptions
  }
}

I've modified your Stackblitz

Post a Comment for "How To Update A Reactive Form Field By Button Click On Different Component?"