最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

javascript - Angular 6 multiple @input() level - Stack Overflow

programmeradmin2浏览0评论

I have a ponent that contain multiple level of children ponents :

Parent
  |
Child1
  |
Child2
  |
Child3

I'm trying to pass a value from parent to each children through @Input()

So for example in the parent I have this :

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

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

In the Template I set :

[info]="info"

Each child have the same input as the parent.

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

I have a ponent that contain multiple level of children ponents :

Parent
  |
Child1
  |
Child2
  |
Child3

I'm trying to pass a value from parent to each children through @Input()

So for example in the parent I have this :

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

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

In the Template I set :

[info]="info"

Each child have the same input as the parent.

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

Share Improve this question asked Oct 25, 2018 at 14:51 An-droidAn-droid 6,48510 gold badges51 silver badges95 bronze badges 3
  • 1 IS child 2 a child ponent of Child 1 and child 3 a chld ponent of child 2? – SiddAjmera Commented Oct 25, 2018 at 14:53
  • as @SiddAjmera mentioned, according to your diagram, child 2 is basically the child of child 1 and grandchild of parent.. is that correct? – reddevilzee Commented Oct 25, 2018 at 14:54
  • 3 SharedService is the perfect solution for this – djain4 Commented Oct 25, 2018 at 15:03
Add a ment  | 

1 Answer 1

Reset to default 9

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. Pass the @Input from Child 1 to Child 2 in Child 1's template.

  2. 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.

I'd remend 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);
  }
}

And then in all the Child Components:

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

评论列表(0)

  1. 暂无评论