angular - 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)?
解决方案
我已经分享了您问题的解决方案。在这里检查
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
});
}
}
推荐阅读
- java - 使用 Cargo 插件将 Web 应用程序部署到远程服务器
- xcode - VideoCloudSamplePlayer iOS 示例应用程序视频再现
- c# - 使用 DbConnection 作为属性,只有 get 或 as 方法
- sql - 我有一个名为 authorsjson 的 JSON 列,其中包含 json 数据。我想找到名称以给定字符串开头的所有用户
- go - 按 mime 类型获取文件扩展名
- java - 不正确地显示图表
- android - 从活动中访问 viewpager 的片段
- django - 预测时出现张量流错误的 Keras
- ios - Swift - 如何在 if 语句之外访问常量
- powershell - 使用 Get-WmiObject 使用示例监视 CPU