2017-09-21 45 views
1

這是我父母組件的html模板。 自定義標記包含我的子組件以顯示發佈對象 我已連接快速服務器,並且所有查詢均通過HTTP與服務完成。 每次添加新的發佈對象時,UI都不會更新。Angular 4 - 從父項到子項的綁定事件

我知道我需要將事件傳遞給子組件,但迄今爲止我還沒有成功。

/* * app.component.html/ 在這個模板我試圖綁定(onAdded回調函數裏)的方法= 「onAdded回調函數裏($事件)」

<div class="collapse navbar-collapse" id="navbarSupportedContent"> 

    <ul class="navbar-nav mr-auto links"> 
     <li class="nav-item"> 
     <a class="btn btn-secondary" routerLink="/posts" href="javascript:void(0);" (click)="addToBoard()"> <i class="fa fa-plus-square fa-3x" aria-hidden="true"></i></a> 
     </li> 
    </ul> 

    </div> 

</div> 

/* app.component.ts(父)*/

import { Component, OnInit, **EventEmitter, Output**} from '@angular/core'; 
import { Post } from './shared/post'; 
import { PostService } from './services/post.service'; 

@Component({ 
    selector: 'app-root', 
    templateUrl: './app.component.html', 
    styleUrls: ['./app.component.css'], 
    providers: [PostService] 
}) 
export class AppComponent implements OnInit { 
    @Output() onAdded = new EventEmitter<Post>(); 
    title = 'Post it Board'; 
    posts: Post[]; 
    private newPost :Post; 
    constructor(private postService: PostService) { } 

    ngOnInit(): void { 
    this.getPosts() 
    this.newPost = { 
     text: 'some text', 
     _id: '' 

    } 
    } 


    addToBoard(): void { 
    this.postService.addPost(this.newPost).subscribe(
     response=> { 
      if(response.success== true) 
      //If success, update the view-list component 
      console.log('success') 
      **this.onAdded.emit(this.newPost);** 
     }, 
    ); 
    } 

    getPosts() { 
    this.postService.getAllPosts().subscribe(
     response => this.posts = response,) 
    } 

} 

/視圖board.component.ts(兒童)/

import { Component, OnInit} from '@angular/core'; 
import { Post } from '../shared/post'; 
import { POSTS } from '../shared/mock-posts'; 
import { PostService } from '../services/post.service'; 

@Component({ 
    selector: 'view-board', 
    templateUrl: './view-board.component.html', 
    styleUrls: ['../css/style.css'], 
    providers: [PostService] 
}) 
export class ViewBoardComponent implements OnInit { 

    title = "Post it" 
    posts: Post[]; 
    constructor(private postService: PostService) { } 

    ngOnInit() { 
    this.getPosts() 
    } 

    getPosts() { 
    this.postService.getAllPosts().subscribe(
     response => this.posts = response,) 
    } 

    **onAdded(post: Post) { 
    console.log('new post added ' + post.text) 
    this.posts = this.posts.concat(post); 
    }** 

} 

感謝您的幫助!

+0

對不起,我發現了一塊代碼的缺失 – SandyL

+0

<視圖板(onAdded回調函數裏)= 「onAdded回調函數裏($事件)」>,我在app.component.html – SandyL

回答

1

不,你必須做事件發送,如果你想從孩子傳遞給父母,在這種情況下,你可以將其作爲輸入傳遞給子元素。

裏面的父組件。

<view-board [success]="success"> 

並在子組件,

@Input() success: string; 
+1

謝謝Sajeetharan做一個事件綁定。我想做事件綁定(不是屬性綁定),並在觸發父組件中的操作後觸發子組件中的方法 – SandyL

+0

您仍然可以這樣做,標記它是否幫助 – Sajeetharan

+0

是。謝謝你的幫助。似乎我不能標記,但一旦我獲得足夠的聲譽標記,我將確保給它一個投票 – SandyL

相關問題