从一个组件调用函数到另一个组件Angularjs 2

2022-01-21 00:00:00 javascript components angular

我想将值从一个组件传递到另一个组件.

I want to pass value from one component to another component.

也就是说,我需要将值从仪表板组件传递给标题组件

i.e., I need to pass value from Dashboard Component to Header Component

这是我的仪表板组件

import{Component}from '@angular/core';
import { Header } from '../../layout/header.component';
export class Dashboard{
showAlert(id : any)
  {
      setItem(id);
  }
}

这是我的 Header 组件

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'header',
  templateUrl: './header.component.html',
})
export class Header{   
  public setItem(id : any)
  {
    console.log('Exported value'+id)
  }
}

但是总是给找不到setItem

我做错了什么,我该如何解决?

What is the mistake i am doing and how can i fix this ?

注意:我在 Angularjs 2 中这样做

Note : I am doing this in Angularjs 2

推荐答案

如果元素引发事件,您可以通过事件绑定来监听它们.参考角度文档 https://angular.io/guide/template-syntax#event-绑定以获得深入的知识.

If the element raises events, you can listen to them with an event binding. Refer to the angular doc https://angular.io/guide/template-syntax#event-binding for in depth knowledge.

仪表板组件

import{Component}from '@angular/core';
import { Header } from '../../layout/header.component';
@Component({
  selector: 'dashboard',
  templateUrl: './dashboard.component.html',
})
export class Dashboard{
  @Output() setItemEvent  = new EventEmitter();

showAlert(id : any)
  {
      this.setItemEvent.emit(id);
  }
}

标题组件

import { Component, OnInit } from '@angular/core';
@Component({
  selector: 'header',
  template: '<dashboard (setItemEvent)="setItem(param)"></dashboard>',
})
export class Header{   
  public setItem(id : any)
  {
    console.log('Exported value'+id)
  }
}

相关文章