【问题标题】:How to get the selected option value from one component to other component in angular 8如何在角度 8 中将选定的选项值从一个组件获取到另一个组件
【发布时间】:2021-01-08 19:56:38
【问题描述】:

我有2个组件,我想将登录组件的选定选项值获取到主组件而不将其存储到本地存储中,一旦您在登录组件中选择选项,选定的选项值应该显示到主组件中。下面是代码

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 } 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 {
  users:any;
  constructor(private router: Router) { }
  @Input() item: string;
  ngOnInit() {
 
  }
 
 onOptionsSelected(value:string){
     console.log("the selected value is " + value);
}
  
}

home.component.ts

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
  getListData: any;
  constructor() { }

  ngOnInit() {
      this.getHeroes();
  }

}

home.component.html

<div>home works</div>

【问题讨论】:

  • 如果您首先在 angular.io 上阅读完整的《英雄之旅》教程,这可能是最好的。

标签: html angular typescript


【解决方案1】:

尝试使用 rxjs observable。您可以使用 behaviorsubject 创建服务,并在调用所选选项时发出值。在 home.component.ts 文件中,您必须订阅服务中声明的行为主题,然后它会在发生更改时通知您的主组件。尝试阅读此链接https://www.learnrxjs.io/learn-rxjs/subjects/behaviorsubject

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-10-25
    • 2020-07-20
    • 1970-01-01
    • 2021-11-04
    • 1970-01-01
    相关资源
    最近更新 更多