【问题标题】:How to get the selected value from one component to other using event emitter in angular 8如何使用角度 8 中的事件发射器将选定值从一个组件获取到另一个组件
【发布时间】:2020-09-26 18:10:31
【问题描述】:

我有 2 个组件,一个登录和另一个主页。当我将下拉菜单更改为登录组件时,选择的值需要显示在主组件中。我已经将 onchange 事件从登录组件发送到主组件并显示值,但我仍然没有将值放入主组件。这是下面的代码

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);
  }
}

【问题讨论】:

    标签: html angular


    【解决方案1】:

    我在 stackblitz 中粘贴了您的代码:https://stackblitz.com/edit/angular-cfkqns

    您被正确地发出值直到父组件并绑定要在父组件中显示的值。

    它正在按照您的预期工作:-)

    更新:

    我在这里为其他人回答了同样的问题:

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

    但是我已经更新了你的 stackblitz 以反映如何实现同样的目标。

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

    【讨论】:

    • 谢谢你的回答,假设我的select html是这样的 在加载主页时我需要显示选中的(第一个选项),在这种情况下需要做什么
    • @anguler-developer 我已经更新了关于您的评论的答案:-)
    猜你喜欢
    • 2021-01-08
    • 1970-01-01
    • 1970-01-01
    • 2017-04-12
    • 1970-01-01
    • 2020-07-20
    • 2016-04-20
    • 2020-10-25
    • 1970-01-01
    相关资源
    最近更新 更多