Angular 4 - 从父组件到子组件的事件绑定

时间:2017-09-21 05:19:32

标签: angular eventemitter event-binding

这是我父组件的html模板。 自定义标记用于包含我的子组件以显示帖子对象 我已连接快速服务器,所有查询都是通过HTTP与服务完成的。 每次添加新的帖子对象时,UI都不会更新。

我知道我需要将事件传递给子组件,但到目前为止我还没有成功。

/ * app.component.html * / 在这个模板中我试图用(onAdded)=“onAdded($ event)”

绑定方法

    

<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(PARENT)* /

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,)   
  }

}

/ view-board.component.ts(CHILD) /

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);
  }**

}

感谢您的帮助!

1 个答案:

答案 0 :(得分:1)

不,如果你想从Child传递给Parent,你必须做事件发送,在这种情况下,你可以作为输入传递给子元素。

内部父组件。

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

并在您的子组件中

@Input() success: string;