【问题标题】:Pass data from one Component to another Component in angular4将数据从一个组件传递到angular4中的另一个组件
【发布时间】:2018-05-04 13:55:02
【问题描述】:

我的 Angular 应用程序中有两个组件(Component1 和 Component2)。我在我的应用程序组件中渲染了这两个组件。 现在我想将一个值从 Component1 发送到 Component2。如何发送。有什么最佳做法吗??

在 Component1 我有这样的代码。 组件1.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);
   }
}

在 Component2.html 我有

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

在 Component2.ts 我有

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 我有这样的代码。

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

现在我要将值从组件 1 发送到组件 2。但是输出中有两次点击按钮。

另一个问题是我想将数据从一个组件传输到另一个组件,该组件位于组件树的同一层次结构中。 通过上述方式,我不会在组件树的同一层次结构中获得组件。

【问题讨论】:

  • 请添加演示您尝试完成的代码。
  • 你在谷歌上搜索过吗?
  • 是的,我进行了搜索。
  • @roopteja 你正在使用事件发射器,看看它,它会很好去

标签: angular angular5


【解决方案1】:

您可以通过三种方式完成相同的操作。

【讨论】:

  • 类似的问题很多,为什么你的回答都一样
  • 可能他是 SO 的初学者,他需要一些帮助才能开始,他可以从那里开始 @Sajeetharan 我看到你也回答了这样的问题
  • 哈哈我做了,但这些天没有。如果他提供代码是有道理的!
  • 我明白了,但如果他是具体的,我可以发表评论,但他不必回答。你 DV 如果你想我会把它取下来
  • Sajeetharan 我附上了代码和我的问题。请查看并回答。提前致谢
【解决方案2】:

如果您将数据从父组件传递到子组件,您应该使用 @input

在您的情况下,您希望将数据从一个组件传递到同一级别的另一个组件。我建议你去共享服务。

查看此 answer 了解更多详情。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2018-05-02
    • 2019-12-16
    • 2021-04-16
    • 2019-11-06
    • 1970-01-01
    相关资源
    最近更新 更多