Pass data from one Component to another Component in angular4

偶尔善良 提交于 2020-01-09 12:02:20

问题


I have two Components(Component1 and Component2) in my Angular Application. These two components I have rendered in my app component. Now I want to send a value from Component1 to Component2. How to Send it. Are there any best practices??

In Component1 I have a code Like this. Component1.html

<button (click)="passData()">Click Me</button>

Component1.ts

import { Component, OnInit , Output , EventEmitter } from '@angular/core';
@Component({
  selector: 'app-component1',
  templateUrl: './component1.component.html',
  styleUrls: ['./component1.component.css']
})
export class Component1Component implements OnInit {

   Component1Variable:string="Component1VariableSent";
  constructor() { }
  ngOnInit() {
  }
   @Output()
   SendValue=new EventEmitter<string>();
   passData()
   {
        this.SendValue.emit(this.Component1Variable);
   }
}

In Component2.html I have

<app-component1 (SendValue)="ValueFromComp1($event)"> </app-component1>
{{ValueFromComponent1}}

In Component2.ts I have

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-component2',
  templateUrl: './component2.component.html',
  styleUrls: ['./component2.component.css']
})
export class Component2Component implements OnInit {
  ValueFromComponent1:any;
  constructor() { }

  ngOnInit() {
  }
  ValueFromComp1(var1:any)
  {
      this.ValueFromComponent1=var1;
  }

}

In appcomponent.html I hav code Like this.

<app-component1></app-component1>
<app-component2></app-component2>

Now I am getting to send the value from component1 to component2. But there is a click button two times in the output.

And another question is that I want to transfer data from one Component to another Component which resides in the same hirearchy of component tree. By doing in the above way I am not getting the components in the same hirearchy of component tree.


回答1:


There are three ways you can accomplish the same .

  • Event Emitters (For cases where components have parent child relation ship)
  • Shared Services
  • Ngrx (a more expansive shared service for large projects)



回答2:


If you are passing data from parent component to your child component you should use @input.

In your case you want to pass data from one component to another which are in the same level. i would suggest you to go for shared service.

Look at this answer to get more details.



来源:https://stackoverflow.com/questions/47407391/pass-data-from-one-component-to-another-component-in-angular4

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