转载自 http://www.ngui.cc/news/show-118.html
Output 装饰器的作用是用来实现子组件将信息,通过事件的形式通知到父级组件。
在介绍 Output 属性装饰器前,我们先来介绍一下 EventEmitter 这个幕后英雄:
let numberEmitter: EventEmitter<number> = new EventEmitter<number>();
numberEmitter.subscribe((value: number) => console.log(value));
numberEmitter.emit(10);
接下来我们来介绍如何使用 Output 装饰器。
使用 Output 装饰器
更新 SimpleFormComponent 组件
import {Component, OnInit, Input, Output, EventEmitter} from '@angular/core';
@Component({
selector: 'app-simple-form',
template: `
<div>
{{message}}
<input #myInput type="text" [(ngModel)]="message">
<button (click)="update.emit({text: message})">更新</button>
</div>
`,
styles: []
})
export class SimpleFormComponent implements OnInit {
@Input() message: string;
@Output() update = new EventEmitter<{text: string}>();
ngOnInit() { } }
更新 MailService 服务
import {Injectable} from '@angular/core';
@Injectable()
export class MailService {
messages: Array<{id: number, text: string}> = [
{id: 0, text: '天之骄子,Angular 交流群①'},
{id: 1, text: 'Shadows,Angular 交流群①'},
{id: 2, text: 'Keriy,Angular 交流群①'}
];
update(id, text) {
this.messages = this.messages.map(msg => { return msg.id === id ? {id, text} : msg;
});
}
}
更新 AppComponent 组件
import {Component} from '@angular/core';
import {MailService} from "./mail.service";
@Component({
selector: 'app-root',
template: `
<h3>{{title}}</h3>
<ul>
<li *ngFor="let message of mailService.messages;">
{{message.text}}
</li>
</ul>
<app-simple-form *ngFor="let message of mailService.messages;"
[message]="message.text"
(update)="onUpdate(message.id, $event.text)">
</app-simple-form>
` })
export class AppComponent {
title = 'Hello, Angular';
onUpdate(id, text) {
this.mailService.update(id, text);
}
constructor(private mailService: MailService) {}
}
上面示例中,我们仍然使用 (eventName) 事件绑定的语法,监听我们自定义的 update 事件。当在 SimpleFormComponent 组件中修改 input 输入框的文本消息后,点击更新按钮,将会调用 AppComponent 组件类中的 onUpdate() 方法,更新对应的信息。