【问题标题】:Listen to Angular2 Component Events监听 Angular2 组件事件
【发布时间】:2017-02-21 11:31:44
【问题描述】:

Angular2 文档只是关于创建新应用程序,但没有任何关于使用 angular2 将孤立的组件添加到现有网站的内容。重写整个网站不是一种选择。 所以我想创建一个简单的角度组件,例如这样的。

const template = `
    <button (click)="triggerEvent()">Trigger Event</button>
`;

@Component({
    template,
    selector: "poc-comp"
})
export class PocComponent {
    @Output() pocevent: EventEmitter<any>;
    public triggerEvent() {
        this.pocevent.emit("here we go!");
    }
}

然后我有一个包含组件的页面。

<lot-of-html>
<poc-comp (pocevent)="handlerOutsideAngular()"></poc-comp>
<lot-of-other-html>

所以这就是我认为我的工作,但不是。事件只能被角度组件捕获。 我的下一个想法是,使用ElementRef 并使用dispatchEvent,但看起来ElementRef 只提供了一个“损坏”且无类型的HTMLElement。

问题是,是否有可能使用 Angular 创建某种与非 Angular Web 应用程序一起工作的 Web 组件?向组件中插入数据很容易,但我想从组件中得到一些东西。

【问题讨论】:

    标签: angular typescript


    【解决方案1】:

    只是改变

      @Output() pocevent: EventEmitter<any>; 
    

      @Output() pocevent: EventEmitter<any> = new EventEmitter<any>();
    

    那么,

    <lot-of-html>
        <poc-comp (pocevent)="handlerOutsideAngular($event)"></poc-comp>   //<<<===added $event
    <lot-of-other-html>
    
    
    handlerOutsideAngular(value){
       console.log(value)   //here we go!
    }
    

    我不确定

    @Component({
        template,                        <<<====This line I don't know
        selector: "poc-comp"
    })
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-02-28
      • 1970-01-01
      • 1970-01-01
      • 2023-03-14
      • 2015-05-07
      • 2021-12-27
      相关资源
      最近更新 更多