Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

200
Views
Cómo comunicarse entre componentes hermanos cuando uno está siendo cedido por la salida del enrutador

Tengo una ruta dinámica /insights/:id , en cuyo caso la salida de mi enrutador produce un componente de información detallada y necesito mostrar un botón en un componente separado que navega de regreso a /insights cuando se hace clic en él. Necesito que este botón solo aparezca cuando se muestre el componente de información detallada. Mi problema es tratar de entender cómo se comunicarán estos dos componentes hermanos. Puedo hacer que el componente que tiene el botón verifique la URL, pero no sé cómo hacerlo cuando la ruta es dinámica con un parámetro de identificación que siempre cambia.

Así que en su lugar tengo esto:

 ngOnInit() { this.closeIconVisible = false; this.router.events.subscribe(res => { if (res instanceof NavigationEnd) { let fn = this.route.children[0].component; let componentName = fn['name']; if (componentName === 'InsightDetailComponent') { this.closeIconVisible = true; } else { this.closeIconVisible = false; } } }) }

Este enfoque funciona, pero no se siente bien. ¿Alguna sugerencia?

over 4 years ago · Santiago Trujillo
2 answers
Answer question

0

Puede inyectar el componente principal a uno secundario y configurarlo. Aquí está tu ejemplo:

 @Component({ selector: 'my-parent', template: ` <div> parent view <button routerLink="/parent" *ngIf="show">close</button> <a routerLink="/parent/child">Go Child</a> </div> <router-outlet></router-outlet> `, }) export class ParentComponent { show = false; constructor() {} } @Component({ selector: 'my-child', template: ` <div> child view </div> `, }) export class ChildComponent { name:string; constructor(private parentComponent: ParentComponent) {} ngOnInit() { this.parentComponent.show = true; } ngOnDestroy() { this.parentComponent.show = false; } } @Component({ selector: 'my-app', template: ` <a routerLink="/parent">Go Parent</a> <router-outlet></router-outlet> `, }) export class App { name:string; constructor() { this.name = `Angular! v${VERSION.full}` } } let routes = [ { path:"parent", component ParentComponent, children: [ {path:"child", component ChildComponent} ] ]
over 4 years ago · Santiago Trujillo Report

0

Teniendo en cuenta el comentario de Gunter, decidí crear un servicio compartido que configurara una transmisión entre los dos componentes hermanos. La solución final se ve así:

Primero creé un servicio compartido:

 import {Injectable} from '@angular/core'; import {Subject} from "rxjs/Subject"; @Injectable() export class SharedService { private closeIconVisible: Subject<boolean> = new Subject<boolean>(); closeIconVisible$ = this.closeIconVisible.asObservable(); transmitData(data: boolean) { this.closeIconVisible.next(data); } }

Luego configure el extremo receptor de la transmisión en el componente con el botón:

 this.sharedService.closeIconVisible$ .takeUntil(this.ngUnsubscribe) .subscribe( data => { this.closeIconVisible = data; } )

Mientras que el otro componente hermano producido por la salida del enrutador transmite su existencia y pasa un valor usando rxjs Objetos observables:

 ngOnInit() { this.sharedService.transmitData(true); }
over 4 years ago · Santiago Trujillo Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!