Saturday, 25 October 2025

parent to child

 Solution 2: Shared service (recommended for complex applications)

For more complex applications, a shared service with an RxJS Subject or BehaviorSubject is a cleaner solution for decoupled communication. 
1. Create a shared service
The service will hold an observable that other components can subscribe to. 
typescript
// dropdown.service.ts
import { Injectable } from '@angular/core';
import { Subject } from 'rxjs';

@Injectable({
  providedIn: 'root'
})
export class DropdownService {
  private dropdownSubject = new Subject<any>();

  // Observable for other components to subscribe to
  dropdownValue$ = this.dropdownSubject.asObservable();

  // Method to be called by child1 when the dropdown changes
  sendDropdownValue(value: any) {
    this.dropdownSubject.next(value);
  }
}
Use code with caution.
2. Send the value from the first child (app-newhire-header-details)
In newhire-header-details.component.ts, inject the service and call its sendDropdownValue() method.
typescript
import { Component } from '@angular/core';
import { DropdownService } from '../dropdown.service'; // Adjust path

@Component({ ... })
export class NewhireHeaderDetailsComponent {
  constructor(private dropdownService: DropdownService) {}

  onDropdownSelectionChange(value: any) {
    this.dropdownService.sendDropdownValue(value);
  }
}
Use code with caution.
3. Subscribe to the event in the second child (app-personal-tab)
In personal-tab.component.ts, inject the service and subscribe to the observable to get the latest value.
typescript
import { Component, OnInit, OnDestroy } from '@angular/core';
import { DropdownService } from '../dropdown.service'; // Adjust path
import { Subscription } from 'rxjs';
import { YourApiService } from './your-api.service'; // Assume you have an API service

@Component({ ... })
export class PersonalTabComponent implements OnInit, OnDestroy {
  private dropdownSubscription: Subscription;

  constructor(private dropdownService: DropdownService, private yourApiService: YourApiService) {}

  ngOnInit() {
    this.dropdownSubscription = this.dropdownService.dropdownValue$.subscribe(selectedValue => {
      if (selectedValue) {
        this.callApi(selectedValue);
      }
    });
  }

  callApi(value: any) {
    this.yourApiService.getData(value).subscribe(
      (response) => console.log('API response for PersonalTab:', response),
      (error) => console.error('API error:', error)
    );
  }

  ngOnDestroy() {
    // Unsubscribe to prevent memory leaks
    if (this.dropdownSubscription) {
      this.dropdownSubscription.unsubscribe();
    }
  }
}
Use code with caution.

No comments:

Post a Comment

calling or handling data without c# model

 calling or handling data without c# model Yes, it is possible to read data in a C# Web API without explicitly defining model classes for ev...