Skip to content
Advertisement

load data on change of dropdown in other component in Angular

I have component A which is navbar and component B which is list view

Navbar has dropdown where all the users are listed, onInit method of component B all the data is loaded in the Component B Table that selected user is in local storage, now i want when the user changes the users from dropdown then that users data should automatically be refreshed in the Component B selected users are saved in localstorage. Is there anyway i can call method of second component from first component.

Navbar Component

 <select class="form-control"(change)="selectUsers($event)" [(ngModel)]="UserId">
           <option *ngFor="let opt of userlist" value={{opt.UserId}}>{{opt?.userName}}
 </option>
 </select>



 selectUsers(event) {
     this.Service.SelectedUserId = event.target.value;
  }

In Service File

 set SelectedUserId(value: string) {
    if (value) localStorage.setItem('ActiveUserId', value);
  }

Component B:

 fetch() {
    this.Userslist = [];
    this.param.userId = localStorage.getItem('ActiveUserId');
    this.service.getUsers(this.param).subscribe((data => {
      this.Userslist = data.response;
   }
 }

In View:

<tbody>
  <tr *ngFor="let data of Userslist | paginate:{itemsPerPage: 10, currentPage:p} ; let i=index"
..
..
</tbody>

Any solution to resolve this issue, Thanks

Advertisement

Answer

setup a common service which is shared by the two components. Lets assume its called testService.

so service will be like.

export class testService {
    testEmitter: Subject<void> = new Subject<void>()
    testObserver$: Observable<void>;

    constructor () {
        this.testObserver$ = this.testEmitter.asObservable();
    }
}

Now the power of this pattern is that we can listen for next of the subject from any component in the application and perform action!

so in the navbar we start the next which will trigger action on all the observables!

 selectUsers(event) {
     this.Service.SelectedUserId = event.target.value;
    this.testService.next();
  }

So we subscribe on the component where the refresh should happen, and then reload the grid.

child component.

export class ChildComponent implements OnInit, OnDestroy {
    subscription: Subscription = new Subscription();

    ngOnInit() {
        this.subscription.add(
            this.testService.testObserver$.subscribe(() => {
                this.fetch();
            })
        );
    }

    ngOnDestroy() {
        this.subscription.unsubscribe();
    }
}

You can also emit objects like {eventType: 'test', data: {}} inside the next and then add multiple if conditions to validate the eventType and perform multiple actions on the same subject!

User contributions licensed under: CC BY-SA
4 People found this is helpful
Advertisement