组件与 Angular 中的输出互动

输出为子组件提供了一种向其父组件发出事件的机制。

<$>[note]这篇文章涵盖了Angular 2和更高版本<$>

在父组件的模板中,将事件绑定定义为子组件选择器的一部分。绑定应该指向父组件的类中定义的方法,该方法对从子组件接收的数据执行操作。$Event包含从子对象发出的有效负载:

1[label Parent component template: story.component.html]
2<selected-story (selectStory)="getStory($event)">
3</selected-story>
1[label Parent component class: story.component.ts]
2export class StoryComponent {
3  story: string = '';

在子组件中,从@Angel/code导入Output和EventEmitter,并使用@Output修饰符定义您的输出,如下所示:

1[label Child component class: selected-story.component.ts]
2import { Component, Output, EventEmitter } from '@angular/core';
3
4//...
5export class SelectedStoryComponent {
6  story: string;
7  @Output() selectStory = new EventEmitter<string>();

我们的EventEventEventEvent对象有一个emit()方法,它将事件推送到父组件。

现在,在子组件的模板中,您可以定义将发出回父组件的事件绑定:

1[label Child component template: selected-story.component.html]
2<input #storyChoice placeholder="Your fav story">
3<button (click)="onSelectStory(storyChoice.value)">

♪然后请参阅:

Published At
Categories with 技术
Tagged with
comments powered by Disqus