簡體   English   中英

如何在角度分量之間傳遞數據?

[英]How to pass data between angular components?

我不明白為什么我無法在Angular應用程序的兩個組件之間傳遞數據。 這是我所擁有的,但是子組件正在返回“未定義”

我創建了一個對象數組,該對象數組僅接收一個名為profileFeedPosts的字符串,然后嘗試將其作為“ Post”對象數組傳遞給另一個組件。

個人資料供稿是父級,公共供稿是子級。 也許我缺少有關在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);

您已將console.log放置在組件類之外的全局范圍內,其中this.childFeedPosts不存在。

嘗試將console.log移動到PublicFeedComponent.ngOnInit方法中。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM