【发布时间】:2019-08-27 14:30:30
【问题描述】:
我不明白为什么我无法在我的 Angular 应用程序的两个组件之间传递数据。这是我所拥有的,但子组件返回“未定义”
我创建了一个对象数组,它只接收一个名为 profileFeedPosts 的字符串,并尝试将其传递给另一个组件,再次作为“Post”对象数组。
profile-feed 是父级,public-feed 是子级。也许我错过了一些关于在 Angular 中构建父/子组件的方式?
父组件:
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() {
}
}
父组件 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>
子组件:
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);
【问题讨论】:
-
子组件返回“未定义”这是什么意思。返回未定义的方法是什么?鉴于最后一行不是 PublicFeedComponent 类的任何方法的一部分,代码如何编译?
-
Jack,如果您能在 stackblitz.com 上提供示例代码,那将非常有帮助。
标签: angular