将数据从一个组件传递到 angular4 中的另一个组件 [英] Pass data from one Component to another Component in angular4
问题描述
我的 Angular 应用程序中有两个组件(Component1 和 Component2).我在我的应用程序组件中呈现了这两个组件.现在我想将一个值从 Component1 发送到 Component2.如何发送.有什么最佳做法吗??
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??
在 Component1 中,我有一个这样的代码.组件1.html
In Component1 I have a code Like this. Component1.html
<button (click)="passData()">Click Me</button>
Component1.ts
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);
}
}
在 Component2.html 中我有
In Component2.html I have
<app-component1 (SendValue)="ValueFromComp1($event)"> </app-component1>
{{ValueFromComponent1}}
在 Component2.ts 中我有
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;
}
}
在 appcomponent.html 中,我有这样的代码.
In appcomponent.html I hav code Like this.
<app-component1></app-component1>
<app-component2></app-component2>
现在我要将值从 component1 发送到 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.
推荐答案
您可以通过三种方式完成相同的工作.
There are three ways you can accomplish the same .
这篇关于将数据从一个组件传递到 angular4 中的另一个组件的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!