Reputation: 421
I can't understand why I'm unable to pass data between two of the components in my Angular app. Here is what I have, but the child component is returning "undefined"
I am created an array of objects that simply take in a string, called profileFeedPosts, and trying to pass that to another component, again as an array of "Post" objects.
profile-feed is the parent, and public-feed is the child. Perhaps I'm missing something about the way parent/child components need to be structured in Angular?
Parent component:
import { Component} from '@angular/core';
import { Post } from "../models/post.model"
@Component({
selector: 'app-profile-feed',
templateUrl: './profile-feed.component.html',
styleUrls: ['./profile-feed.component.css']
})
export class ProfileFeedComponent {
postBody = null;
profileFeedPosts: Post[] = [
new Post("hello")
];
showPostBody(){
this.postBody = 1;
}
createPost(){
this.postBody = null;
}
postSubmitted(post: string){
const newPost = new Post(post);
this.profileFeedPosts.push(newPost);
}
constructor() { }
ngOnInit() {
}
}
Parent Component HTML:
<div class="post-body" *ngIf="postBody">
<input id="post" type="text" #userPost placeholder="What's up?">
<button (click)="createPost();
postSubmitted(userPost.value);">Share</button>
</div>
<app-public-feed [childFeedPosts]="profileFeedPosts"></app-public-
feed>
Child Component:
import { Component, Input } from '@angular/core';
import { Post } from '../models/post.model';
@Component({
selector: 'app-public-feed',
templateUrl: './public-feed.component.html',
styleUrls: ['./public-feed.component.css']
})
export class PublicFeedComponent {
@Input() childFeedPosts: Post[];
constructor() { }
ngOnInit() {
}
}
console.log(this.childFeedPosts);
Upvotes: 0
Views: 131
Reputation: 339
You have placed the console.log
outside the component class, into the global scope, where this.childFeedPosts
does not exist.
Try moving the console.log
inside the PublicFeedComponent.ngOnInit
method.
Upvotes: 3