Reputation: 75
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 ?
Upvotes: 1
Views: 68
Reputation: 51
<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>```
Upvotes: 0
Reputation: 22213
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
Upvotes: 1
Reputation: 5301
The code in constructor executes before the component receives the changes, you need to shift the logic to ngOnInit
.
Upvotes: 1