Call function from one component to another component Angularjs 2 [duplicate]

末鹿安然 提交于 2019-12-23 03:36:15

问题


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

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

Here is my Dashboard Component

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

Here is my Header component

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

But it is always giving Cannot find setItem

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

Note : I am doing this in Angularjs 2


回答1:


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.

Dashboard Component

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

Header component

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



回答2:


You can use:

localStorage.setItem('name', 'value');

where name is the variable name you will use to access the value. You can access the value using:

var x = localStorage.getItem('name');



回答3:


You can use event-binding like this :

////First Component
@component({
  selector:'componentA',
})
export class ComponentA{
  yourMethod(yourPassedParameter:any){...}
}

////// Second Component
@component({
  selector:'componentB',
  template: `<button (click)="yourMethod(yourParameter)">click</button>`
)
export class ComponentB{
  @Output() eventLis = new EventEmitter();
  yourMethod(yourParameter:any){...
    this.eventLis.emit(yourData);
  }
}

////Your crosscomponent

@component({
  selector:'crosscomponent',
  template: `<componentA #componentA></componentA>
  <componentB (eventLis)="componentA.yourMethod(yourParameter)"></componentB>`
)
export class crosscomponent{
}


来源:https://stackoverflow.com/questions/45327708/call-function-from-one-component-to-another-component-angularjs-2

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!