0

I have 2 components , one login and other home. When I change drop down into login component ,selected value need to display in home component. I am already emitting the onchange event from login component to home component and displaying the value but still I am not getting the value into home component.Here is the code below

login.component.html

<select #mySelect (change)="onOptionsSelected(mySelect.value)">
<option value="one">one</option>
<option value="two">two</option>
</select>

login.component.ts

import { Component, OnInit,Input,Output, EventEmitter } from '@angular/core';
import { Router } from '@angular/router'; 
@Component({
  selector: 'app-login',
  templateUrl: './login.component.html',
  styleUrls: ['./login.component.css']
})
export class LoginComponent implements OnInit {
@Output() buttonClicked = new EventEmitter();
  constructor(private router: Router) { }
  @Input() item: string;
  ngOnInit() {
  }
onOptionsSelected(value:string){
     console.log("the selected value is " + value);
     this.buttonClicked.emit(value);
     this.router.navigateByUrl('/home');
}
}

home.component.html

<p>home works!</p>
<app-login (buttonClicked)='showNextComponent($event)'></app-login>
<p>Hello {{ name }} </p>

home.component.ts

import { Component, OnInit,ElementRef,ViewChild } from '@angular/core';
import { CommonserviceService } from './../utilities/services/commonservice.service';
import { LoginComponent } from '../login/login.component';
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  getListData: any;
  constructor(private commonserviceService: CommonserviceService) { }
  name:string
  ngOnInit() {
     
  }

showNextComponent(value:string) {
    this.name = value;
    console.log(this.name);
  }
}

1 Answers1

0

I pasted your code here in stackblitz: https://stackblitz.com/edit/angular-cfkqns

You are correctly emitted values up to the parent component and binding the value to be displayed in the parent component.

It is working how you expect it to :-)

UPDATE:

I have answered the same question for some one else here:

https://stackoverflow.com/a/64082745/450388

however I have updated your stackblitz to reflect how to achieve the same.

https://stackblitz.com/edit/angular-cfkqns

Adamski
  • 839
  • 2
  • 10
  • 28
  • Thanks for your answer, suppose my select html is like this and on load of home page I need to display selected(first option), in that case what needs to be done – anguler-developer Sep 27 '20 at 05:15
  • @anguler-developer I have updated the answer with regards to your comment :-) – Adamski Sep 27 '20 at 06:38