Angular 5 从组件的子组件之一访问组件
Angular 5 Data Access to Component from one of the component's child
我有以下组件结构;
- RecipeDetailComponent
- 配方列表组件
- RecipeItemComponent(此组件是 RecipeList 的子组件)
- 配方组件
并希望将数据 RecipeItemComponent 传递给 RecipeDetailComponent。
这样做的主要方法是在 RecipeItemComponent 中创建 @Output(),从 RecipeListComponent 获取数据并使用 @Output()。最后使用 属性 绑定通过 RecipeComponent 使用 @input() 从 RecipeDetailComponent 获取数据。
有什么有效的方法或简单的方法吗?我们是否必须跨越父组件才能从子组件获取数据到 RecipeDetailComponent?
提前致谢
我的解决方案是创建一个公共 Recipe 服务,它已将参数作为 Subject 类型的对象传递,并将此服务注入到父组件和子组件中,当我导航到子组件时,我会通知
/// service
export class SharedService {
passedParamter: Subject<any> = new Subject<any>();
notify(data) {
this.passedParamter.next(data);
}
}
//// in parent Component
@Component({
...,
providers:[SharedService]
})
export class RecipeListComponent implements OnInit {
constructor(private SharedService: SharedService){}
ngOnInit() {
}
navigateToChild() {
this.SharedService.notify(data);
}
}
//// in child Component
.
.
.
export class RecipeItemComponent implements OnInit {
constructor(private SharedService: SharedService){}
ngOnInit() {
this.SharedService.passedParamter.subscribe(
data => {
/// here you will recive the data
}
)
}
}
我有以下组件结构;
- RecipeDetailComponent
- 配方列表组件
- RecipeItemComponent(此组件是 RecipeList 的子组件)
- 配方组件
并希望将数据 RecipeItemComponent 传递给 RecipeDetailComponent。 这样做的主要方法是在 RecipeItemComponent 中创建 @Output(),从 RecipeListComponent 获取数据并使用 @Output()。最后使用 属性 绑定通过 RecipeComponent 使用 @input() 从 RecipeDetailComponent 获取数据。
有什么有效的方法或简单的方法吗?我们是否必须跨越父组件才能从子组件获取数据到 RecipeDetailComponent?
提前致谢
我的解决方案是创建一个公共 Recipe 服务,它已将参数作为 Subject 类型的对象传递,并将此服务注入到父组件和子组件中,当我导航到子组件时,我会通知
/// service
export class SharedService {
passedParamter: Subject<any> = new Subject<any>();
notify(data) {
this.passedParamter.next(data);
}
}
//// in parent Component
@Component({
...,
providers:[SharedService]
})
export class RecipeListComponent implements OnInit {
constructor(private SharedService: SharedService){}
ngOnInit() {
}
navigateToChild() {
this.SharedService.notify(data);
}
}
//// in child Component
.
.
.
export class RecipeItemComponent implements OnInit {
constructor(private SharedService: SharedService){}
ngOnInit() {
this.SharedService.passedParamter.subscribe(
data => {
/// here you will recive the data
}
)
}
}