這是我父母組件的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);
}**
}
感謝您的幫助!
對不起,我發現了一塊代碼的缺失 – SandyL
<視圖板(onAdded回調函數裏)= 「onAdded回調函數裏($事件)」>,我在app.component.html – SandyL