infodev
infodev

Reputation: 5235

Angular passing data from parent to child is undefined

I'm trying to use component interaction to pass data from parent to child

In parent component:

<app-news [leonardType]="countTitle"></app-news>

Child component

export class NewsComponent implements OnInit, AfterViewChecked {

  @Input() leonardType: string;
  title;
  constructor(
    public newsService: NewsService
  ) {}
  ngAfterViewChecked() {
    console.log(this.leonardType); ==> undefined
    console.log(this.newsService.leonardCategory[this.leonardType]); ==> undefined
  }

  ngOnInit() {
    this.title = this.newsService.leonardCategory[this.leonardType];
    console.log(this.leonardType); ==> undefined
    console.log(this.newsService.leonardCategory[this.leonardType]); ==> undefined
}

In child component service I have an object:

leonardCategory = {
  countTitle: "TITLE 1",
  indTitle: "TITLE 2"
};

I think that the view is not yet rendered but either in ngAfterViewChecked I get undefined output of leonardType

Upvotes: 2

Views: 3749

Answers (2)

Sagar M
Sagar M

Reputation: 1376

use *ngIf="isLoading$ | async" in parent component to check whether data from backend is still loading or loading completed, once data loaded completely in parent component, the data will be passed to child component

Upvotes: 0

Suren Srapyan
Suren Srapyan

Reputation: 68635

If you want to pass countTitle text, just wrap it into ''. Without '' it is considered as a property in the component which is undefined, so why you get undefined in the child component.

<app-news [leonardType]="'countTitle'"></app-news>

or just without []

<app-news leonardType="countTitle"></app-news>

Upvotes: 3

Related Questions