Angular pass variables between components without inheritance [duplicate]

0

I have a NavBar component with a dropdown and another component that will display a content depending on what is selected in that dropdown.

The problem is that I do not know how to pass that selected from the NavBar component to the component it displays.

I have seen this question: Communication and States between ANGULAR 2 components which says to do a service with which I subscribe to the navbar from the counter and in the navbar change the observable. Also the user @KarlosCode comments: "Redux just does that elevated to the maximum expression".

What would that service be like? Do you recommend Redux? if so, do you know of any example for this case?

    
asked by PriNcee 24.05.2017 в 13:14
source

1 answer

1

If in your main component, let's call it Component SHELL is your Component NAVBAR and your Component CONTENT and your navbar component em> does not handle routes but data you can do that when you click on any item in the dropdown, save the data from the list of data you are handling in a variable of your navbar component , let's call it dataSelected , then you should only have in your component content an input variable with decorator @Input that will receive this DataSelected when detecting a new change and will do the same I have to do.

  

Representative HTML

<app-shell-component>
  <app-navbar-component>
    <ul>
      <li *nfFor="let dato of datos" (click)="datoSeleccionado = dato">
        {{ dato | json }}
      </li>
    </ul>
    <app-contenido-component [dato]="datoSeleccionado"></app-contenido-component>
  </app-navbar-component>
</app-shell-component>
  

CONTENT Component

@Component()
export class ContenidoComponent implements OnChanges {

  @Input() dato = null;

  ngOnChanges(changes) {
    if (changes['dato']) {
      // Aquí ya sabes que has recibido un nuevo dato desde cualquier componente.
      const nuevoDato = changes.dato;
    }
  }

}
    
answered by 13.08.2017 в 14:55