将一个组件传递到另一组件的角度

时间:2019-04-22 05:37:50

标签: angular

我是angular的新手,我基本上是想将一个组件传递给模板中的其他组件。 我通过ng new new-proj

创建了一个新的ng项目

这是我的代码

//contents inside app.component.html

<app-g-table [inputVariable] = "data"> //Table Component
  <app-g-column [name]="'Employee'"></app-g-column> //Column Component
</app-g-table>

 I need to get the data of Column Component[app-g-column] (in this example 
 'Employee') inside app-g-table.ts

有什么办法可以做到这一点?


更新
1.我正在开发自己的通用数据表,可以使用上述语法来实现。
2.在上面的示例中,我最终将传递列组件的列表, 像这样

 <app-g-table [inputVariable] = "data"> //Table Component
      <app-g-column [name]="'Employee'" [isVisible]="true"></app-g-column> //Column Component
      <app-g-column [name]="'Age'" [isVisible]="false"></app-g-column> //Column Component
</app-g-table>

我想知道我是否可以直接在(app-g-table)内部直接使用组件(app-g-column)?

2 个答案:

答案 0 :(得分:1)

我已经分享了您问题的解决方案。 检查这里

https://stackblitz.com/edit/angular-xuxd7a

OR

首先,创建一个sharedService

import { Injectable } from '@angular/core';
import {  Subject  } from 'rxjs';


@Injectable()
export class SharedService {

  myData: Subject<any> = new Subject<any>();

  constructor() {}

  setData(data) {
    this.myData.next(data);
  }
}

然后从要设置数据的位置使用此方法:

export class Component1 implements OnInit {

    constructor(private sharedService: SharedService) { }

    ngOnInit() {
       this.sharedService.setData(data);
    }
}

然后在Component2中要显示数据的位置:

export class Component2 implements OnInit {

  constructor(private sharedService: SharedService) {
    this.sharedService.myData.subscribe((value) => {
     console.log(value) // Here you will get your complete data
    });
  }

}

答案 1 :(得分:0)

为了在Angular中的组件之间传递数据,您应该使用Input和Output,下面有一个链接,它可以帮助您深入了解在组件之间传递数据和事件:

https://angular.io/guide/component-interaction