Here is a snippet of code from my component:
import { Component, OnInit } from '@angular/core';
import { HttpClient } from '@angular/common/http';
@Component({
selector: 'app-home',
templateUrl: './home.component.html',
styleUrls: ['./home.component.css']
})
export class HomeComponent implements OnInit {
public blogposts: Array<any> = [];
constructor(private http: HttpClient) { }
ngOnInit() {
this.http.get("http://localhost:8080/demo/all").
subscribe(function(data){
this.blogposts=data;
console.log(this.blogposts[0]);
})
}
}
The issue I'm facing is that Console.log(this.blogposts[0])
correctly logs the first object in the array. However, when I try to access it in the component template, it becomes undefined.
My component's template structure is as follows:
<div class="row">
<div class="col-sm-6">
</div>
<div class="col-sm-6">
<div class="row">
<div class="col-sm-6">
<app-blog-post *ngIf="blogposts[0]" [title]="blogposts[0].title"></app-blog-post>
</div>
<div class="col-sm-6">456</div>
</div>
<div class="row">
<div class="col-sm-6">123</div>
<div class="col-sm-6">456</div>
</div>
</div>
</div>
When using
<app-blog-post *ngIf="blogposts[0]" >
, nothing gets displayed. If I use <app-blog-post *ngIf="blogposts" >
, an empty <app-blog-post>
gets displayed instead. Removing *ngIf
displays the default value 'abc' assigned to title.
The child component code looks like this:
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-blog-post',
templateUrl: './blog-post.component.html',
styleUrls: ['./blog-post.component.css']
})
export class BlogPostComponent implements OnInit {
ngOnInit() {
}
@Input() title:String="abc";
}
The template for the child component includes:
<div>{{title}}</div>
Even though the parent component contains an array of blogpost objects, accessing blogposts[0]
in the template results in undefined. The blogpost exists but its content objects are inaccessible from the template. Why does this occur?