美文网首页
angular@Output用法

angular@Output用法

作者: 春木橙云 | 来源:发表于2019-10-08 09:30 被阅读0次

子组件中的内容如何传递出去给父组件使用呢?@Output用法整理如下,以备后查!

angular提供了EventEmitter用来触发自定义事件。子指令创建一个 EventEmitter 实例,并将其作为输出属性导出。子指令调用已创建的 EventEmitter 实例中的 emit(payload)方法来触发一个事件,父指令通过事件绑定(eventName)的方式监听该事件,并通过 $event 对象来获取payload对象。

具体用法如下:

  • 父组件
//parent.component.ts
import { Component, Input } from '@angular/core'

@Component({
    selector: 'parent',
    templateUrl: './parent.component.html'
})

export class ParentComponent {
  getChildData(data){
    console.log('childData传进来了', data)
  }
}

//parent.component.html
    <div>
        <child (putChildData)="getChildData($event)"></child>
    </div

  • 子组件
//child.component.ts
import { Component, Input } from '@angular/core';

@Component({
  selector: 'child',
  templateUrl: './child.component.html'
})

export class ChildComponent {
  childData={
    childString: 'output'
  }
  @Output() putChildData: <EventEmitter>any = new Eventmitter<any>();
   ngOnInit(){
    this.putChildData.emit(this.childData);
   }
}

另外,Output 装饰器支持一个可选的参数,用来指定组件绑定属性的名称。如果没有指定,则默认使用 @Output 装饰器,装饰的属性名。

the end!

相关文章

网友评论

      本文标题:angular@Output用法

      本文链接:https://www.haomeiwen.com/subject/guvxyctx.html