[Angular] Communicate with Angular Elements using Inputs and Events

在实际场景中,需与嵌入静态HTML站点的Angular元素通信。此博客介绍了如何向自定义元素传递数据,以及如何以自定义事件形式注册Angular元素的输出,还提及了事件监听相关内容。

In a real world scenario we obviously need to be able to communicate with an Angular Element embedded into our static HTML site. In this lesson we will learn how we can pass data into a Custom Element and how we can register to an Angular Element’s output in the form of custom events.

 

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';

@Component({
  // selector: 'do-greet',
  template: `
    <div>Hi, {{ name }}!</div>
    <button (click)="doGreet()">Greet</button>
  `,
  styles: []
})
export class GreeterComponent implements OnInit {
  @Input() name;
  @Output() greet = new EventEmitter();

  constructor() {}

  doGreet() {
    this.greet.emit(`Hi, ${this.name}`);
  }

  ngOnInit() {}
}

 

Listening for the events:

<html>
  <body>
    <do-greet name="Juri"></do-greet>

    <script src="./polyfills.js"></script>
    <script src="./ngelements.js"></script>
    <script>
      const el = document.querySelector('do-greet');
      el.addEventListener('greet', ev => {
        alert(ev.detail); // get the event output from 'detial'
      });
    </script>
  </body>
</html>

 

转载于:https://www.cnblogs.com/Answer1215/p/10559764.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值