将数据从一个组件传递到angular4中的另一个组件 [英] Pass data from one Component to another Component in angular4

查看:185
本文介绍了将数据从一个组件传递到angular4中的另一个组件的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的Angular应用程序中有两个Components(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中,我有一个像这样的代码. Component1.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屋!

查看全文
相关文章
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆