【问题标题】:How to create a custom event in Angular, within same component?如何在同一个组件中在 Angular 中创建自定义事件?
【发布时间】:2021-11-08 10:35:34
【问题描述】:

是否可以在 Angular 中创建自定义事件,在同一组件内

我正在尝试在“app.component.html”文件中创建自定义点击事件:

<li (customClick) = "cClick($event)"> Test </li>

然后在 app.component.ts 文件中:

cClick(e){ (alert("custom event clicked!"))}

如何在同一个组件中实现这种调用?请帮忙:)

【问题讨论】:

  • 是否有特定用途来覆盖此事件?你能解释一下拥有 customClick 的好处吗,这可能会有所帮助
  • 朋友,只是为了学习目的,我知道如何处理从一个组件到另一个组件的自定义事件。
  • 只是想知道是否可以在同一个组件中处理自定义事件????,所以我想在这里问这个问题。
  • 如果您在示例中记录/警告事件 (e),预期的输出是什么?
  • 我想我对这个事件概念理解不好,事件是用来听的,没有子父组件组合是不可能听的。所以我想我现在明白了,不可能在同一个组件中创建自定义事件:)

标签: javascript angular ionic-framework


【解决方案1】:
<li (customClick) = "cClick($event)"> Test </li>

你必须创建一个指令,在那里你可以监听你想要的任何事件并在你的自定义输出发射器中触发它们

Angular2 Directive to modify click handling

【讨论】:

    【解决方案2】:

    页脚组件

      @Component({
             selector: 'a-footer',
             template: `
               <div>{{footerText}}</div>
               <button ion-button (click)="doIt()">Footer Button</button>
              `
            })
            export class AFooterComponent {
              @Input() footerText:string
              @Output() footerClicked = new EventEmitter()
              
              doIt() {
                this.footerClicked.emit({value:this.footerText})
              }
            }
    

    home.page 组件创建要传递到页脚组件doFooterClicked 的事件处理程序

    @Component({
      selector: 'page-home',
      templateUrl: 'app/home.page.html'
    })
    export class HomePage {
    
      appName = 'Ionic App';
      userCourse =[]
    
      constructor(private navController: NavController) {
        
        this.userCourse = [{CourseName:"course one"},{CourseName:"course two"}]
      }
      
      edit4(_someStuff) {
        
      }
      doFooterClicked(_event) {
        console.log(_event)
        alert("footer clicked "+ _event.value)
      }
    
    }
    

    在 home.page html 中创建组件元素的地方

    <a-footer [footerText]="'someText'"
              (footerClicked)="doFooterClicked($event)">
    </a-footer>`
    

    【讨论】:

      猜你喜欢
      • 2023-03-06
      • 2012-07-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-06-17
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多