Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
710 views
in Technique[技术] by (71.8m points)

angular - Pass data from one Component to another Component in angular4

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

There are three ways you can accomplish the same .


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...