Angular 6多个@input()级别 [英] Angular 6 multiple @input() level

查看:570
本文介绍了Angular 6多个@input()级别的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个包含多个子级组件的组件:

I have a component that contain multiple level of children components :

Parent
  |
Child1
  |
Child2
  |
Child3

我正试图通过<$将父母的值传递给每个孩子c $ c> @Input()

所以例如在父母中我有这个:

So for example in the parent I have this :

@Input() info: Info= {} as Info;

它在父母的 ngOnInit 中初始化组件和值是正常的,我检查了它。

It is initialized in ngOnInit of the parent component and the value is OK, I checked it.

在我设置的模板中:

[info]="info"

每个孩子的输入与parent。

Each child have the same input as the parent.

该值已经传递给 Child1 ,但来自 Child2 Child3 值保持为空,怎么样?

The value is correclty passed to the Child1 but from the Child2 to Child3 the value stay empty, how is that ?

推荐答案

您不能从 ParentCompoennt @Input 属性传递给子组件的子组件。要做到这一点,你有两种方法:

You can't pass an @Input property to the Child of a Child Component from the ParentCompoennt. To do that, you have two ways:


  1. 传递 @Input 从Child 1的模板中的Child 1到Child 2。

  1. Pass the @Input from Child 1 to Child 2 in Child 1's template.

创建一个SharedService,它将作为Parent,Child1,Child2和Child3中的依赖项注入。在Parent中,设置该属性,然后在Child1,Child2和Child 3中获取该属性。

Create a SharedService which will be injected as a dependency in Parent, Child1, Child2 and Child3. From the Parent, set that property and then get that property in Child1, Child2, and Child 3.

我' d建议使用SharedService approch。

I'd recommend using the SharedService approch.

import { BehaviorSubject, Observable } from 'rxjs';
...
export class SharedService {
  private input: BehaviorSubject<any> = new BehaviorSubject<any>(null);
  public input$: Observable<any> = this.resultList.asObservable();

  setInput(input) {
    this.input.next(input);
  }
}

然后在所有子组件中:

input: any;
...
constructor(private sharedService : SharedService ) {}
...
ngOnInit() {
  this.sharedService.input$.subscribe(input => this.input = input);
}

这篇关于Angular 6多个@input()级别的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆