Search code examples
angulareventemitterevent-binding

Angular 4 - event binding from parent to child component


this my html template for the parent component. the custom tag is to include my child component to display post objects I have connected express server and all queries are done via HTTP with a service. Each time I add a new post object, the UI does not update.

I understand that I need to pass event to the child component, but I have not been successful so far.

/* app.component.html */ in this template I am trying to bind the methods with (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);
  }**

}

Thanks for your help!


Solution

  • Nope, you have to do event Emitting if you want to pass from Child to Parent, in this case, you can just pass as an input to the child element.

    Inside Parent component.

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

    and in your child component,

    @Input() success: string;