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
						
Would you have an example? .
– Rebeca Nonato
Follow this tutorial by Ngrx for component-to-component reactive functions: https://ngrx.io/guide/store#tutorial
– Daniel 101