angular @Output 装饰器

转载自  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() 方法,更新对应的信息。

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值