首页 > 解决方案 > Angular 将一个组件传递给其他组件

问题描述

我是 Angular 的新手,我基本上是在尝试将一个组件传递给模板中的另一个组件。我通过创建了一个新的 ng 项目ng new new-proj

这是我的代码

//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)?

标签: angular

解决方案


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

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

或者

一、创建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
    });
  }

}


推荐阅读