Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
120 views
in Technique[技术] by (71.8m points)

javascript - Angular 6 multiple @input() level

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

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 component 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 ?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 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);
  }
}

And then in all the Child Components:

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...