Send Id via Independent Components from a Link and Miter, Angular 2 (7)?

Asked

Viewed 78 times

0

I need to communicate between two components. From a selection (First Component), I send the ID to the other component, in ngOnInit I receive the value of this ID (Second Component), but when I try to use it in another function (concluirCadastro()), gives Indefinid. What can I do? How to resolve the issue?

Code available on: https://stackblitz.com/edit/angular-7rhqrp

In the HTML of the First Component

<h4>Selecionar Cidade</h4>
<mat-form-field>
  <mat-label>Cidade</mat-label>
  <mat-select (selectionChange)="cidadeSelecionada($event.value)">
    <mat-option *ngFor="let city of citys" [value]="city.Id">
      {{city.NomeCity}}
    </mat-option>
  </mat-select>
</mat-form-field>

<a [routerLink]="['/ParentChild2']">Selecionar</a>

In the Component.ts of the First Component

static emitirIdCidade = new EventEmitter<string>();

  citys: City[] = [
    {Id: 0, NomeCity: 'Belo Horizonte'},
    {Id: 1, NomeCity: 'Lavras'},
    {Id: 2, NomeCity: 'Rio de Janeiro'}
  ];


  cidadeSelecionada(event){
    ParentChildComponent.emitirIdCidade.emit(event);
  }

In the HTML of the Second Component

<button (click)="concluirCadastro()">Concluir Cadastro</button>

In the Component.ts of the Second Component

 ngOnInit() {
    ParentChildComponent.emitirIdCidade.subscribe(
      id => console.log(id)
    );
  }

  concluirCadastro() {
    console.log("teste novamente - " + this.cidadeId);
  }

Console result.

0

teste novamente - undefined

2 answers

1

Instead of calling the emitter variable statically [Parentchildcomponent.emitirIdCidade.Emit(Event);]. I advise you to create a Service, within it you place your Eventemitter variable and initialize your service in the two components and do your desired action.

Tip: Instead of using this way with Service, use Ngrx (Redux).

  • Would you have an example? .

  • 1

    Follow this tutorial by Ngrx for component-to-component reactive functions: https://ngrx.io/guide/store#tutorial

0


Browser other questions tagged

You are not signed in. Login or sign up in order to post.