将数据传递给Angular中的子组件

时间:2018-01-21 12:16:01

标签: angular

我看过很少有关于这个问题的话题,但还没有找到解决方案。

这是父组件:

import { Component, OnInit } from '@angular/core';
import { DataService } from '../../services/data.service';
import { ActivatedRoute } from '@angular/router';

@Component({
  selector: 'app-story',
  templateUrl: './story.component.html',
  styleUrls: ['./story.component.css']
})
export class StoryComponent implements OnInit {
  story: Story;
  name: string;
  text: string;
  storyID: string = '25252521512523';

  constructor(private dataService:DataService) { }

  ngOnInit() {
    this.dataService.getStory({id: this.storyID}).subscribe((story) => {
      this.story = story;
    });
  }

}

interface Story {
  author: string,
  story: string,
  image: string
}

interface Comment {
  name: string,
  text: string
}

父组件在此处向子组件提供数据。这是父组件的html:

<div *ngIf="story" style="text-align: center">
  <app-comments comments={{story.comments}}></app-comments>
</div>

这是子组件:

import { Component, OnInit, Input } from '@angular/core';

@Component({
  selector: 'app-comments',
  templateUrl: './comments.component.html',
  styleUrls: ['./comments.component.css']
})
export class CommentsComponent implements OnInit {
  @Input() comments: Comment[];
}

interface Comment {
  name: string,
  text: string
}

这是子组件的html:

<div *ngIf="comments.length > 1">
  <ul>
    <li *ngFor="let comment of comments; let i = index">
      {{comment.name}}: {{comment.text}}
    </li>
  </ul>
</div>

1 个答案:

答案 0 :(得分:1)

您想使用属性绑定: https://angular.io/guide/template-syntax#property-binding

改变你的代码:

<div *ngIf="story" style="text-align: center">
  <app-comments [comments]="story.comments"></app-comments>
</div>

还在官方教程中显示: https://angular.io/tutorial/toh-pt3