1

这是我的父组件的 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(儿童)/

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

}

谢谢你的帮助!

4

1 回答 1

1

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

内部父组件。

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

在您的子组件中,

@Input() success: string;
于 2017-09-21T05:21:13.530 回答