1

I'm working on my first angular project and my home component html looks like below

<div class="container">
  <div>
    <div class="col-md-4">
      <h1 id="tableLabel">Latest</h1>
      <news-item [section]="Latest"></news-item>
    </div>
    <div class="col-md-4">
      <h1 id="tableLabel">STEM Stuff</h1>
      <news-item [section]="STEM"></news-item>
    </div>
  </div>
</div>

and the ts for news-item is as below

import { Component, Inject, Input } from '@angular/core';

import { HttpClient } from '@angular/common/http';

@Component({
    selector: 'news-item',
    templateUrl: './news-item.component.html',
})

export class NewsItemComponent {

    public newsitems: NewsItem[];

    @Input() section: string;

    constructor(http: HttpClient, @Inject('BASE_URL') baseUrl: string) {

            http.get<NewsItem[]>(baseUrl + 'newsitems/GetNewsItemsBySection/' + this.section).subscribe(result => {

                this.newsitems = result;

            }, error => console.error(error));
    }
}

I'm getting this.section as undefined within the constructor. What am I missing ?

1
  • why have you mapped section as @Input? are you passing some information from <news-item> to the controller? At first instance <news-item> looks like for rendering purpose only. Commented Nov 13, 2019 at 17:46

3 Answers 3

1

Try in within ngOnInit() or ngOnChanges()

The difference between constructor and ngOnInit is that ngOnInit lifecycle hook runs after constructor. Input initial values aren't available in constructor, but they are available in ngOnInit

Sign up to request clarification or add additional context in comments.

Comments

1

The code in constructor executes before the component receives the changes, you need to shift the logic to ngOnInit.

Comments

0

<news-item [section]="STEM"></news-item>

Angular will interpolate this as value of STEM, and STEM is not defined home component. so the section in news-item component is undefined

<news-item section="STEM"></news-item>

This will interpolate as STEM as a string not an variable.

I hope this will work for you.

  <div>
    <div class="col-md-4">
      <h1 id="tableLabel">Latest</h1>
      <news-item section="Latest"></news-item>
    </div>
    <div class="col-md-4">
      <h1 id="tableLabel">STEM Stuff</h1>
      <news-item section="STEM"></news-item>
    </div>
  </div>
</div>```

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.