通过 Angular 组件将函数作为参数传递给 (click) 事件

Pass a function as a parameter to (click) event through Angular component

我正在尝试创建一个带有取消和发送按钮的组件,以避免在每个表单上使用 c&p,但我找不到将函数作为参数传递给组件选择器的方法

HTML:

<btn-submit [cancelFunction]='test' [acceptFunction]='test'></btn-submit>

TS Parent:

test = () => console.log("this is a test");

TS Child:

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

@Component({
  selector: 'btn-submit',
  styleUrls: ['./btn.component.scss'],
  template: `
          <button class="btn" click="cancelFunction()">
              <fa name="times"></fa>
          </button>
          <button class="btn" click="acceptFunction()">
              <fa name="check"></fa>
          </button>
  `
})

export class BtnSubmitComponent {
  @Input() cancelFunction: any;
  @Input() acceptFunction: any;
}

将其从 @Input 更改为 @Output

@Output() acceptFunction = new EventEmitter<any>();

然后,当您想要调用它时,在您的组件内部执行:

this.acceptFunction.emit();

HTML可以保持原样。

    <btn-submit (cancelFunction)="myCancelFunction()"
            (sendFunction)="mySendFunction()></btn-submit>

每次调用 .emit(),它都会触发一个事件。 parent 将听到此事件,并调用您绑定的函数(例如 mySendFunction

如果您想真正将一个函数从父组件传递到子组件,您可以按照下面的代码所示进行操作。

但是使用其他答案中显示的更常见的 @OutputEventEmitter 方法可能是更好的选择。 @Output 技术不允许你传入一个函数,但允许你的父组件接收来自子组件的事件,你可以通过调用父组件中的函数来响应这些事件。

这是允许您将函数从父组件传递到子组件的代码。

父组件

test = () => console.log("this is a test");

父模板

<pm-star [rating]='product.starRating'
    [testFunction]='test'
    (ratingClicked)='onRatingClicked($event)'>
</pm-star>

注意方括号(属性 绑定),它不会 调用 函数而是绑定到包含该函数的组件的 属性 .

子组件

  @Input() testFunction: any;

子模板

<div class="crop"
     [style.width.px]="starWidth"
     [title]="rating"
     (click)="testFunction()">

我有一个 stackblitz,这里有一个简单的工作示例:https://stackblitz.com/edit/angular-jwguwk?file=src%2Fapp%2Fapp.component.ts

您可以使用 @Output decorator in conjunction with EventEmitter class 来实现这个

子组件(Typescript 和标记)

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

        @Component({
          selector: 'btn-submit',
          styleUrls: ['./btn.component.scss'],
          template: `
                  <button class="btn" click="cancelFunction()">
                      <fa name="times"></fa>
                  </button>
                  <button class="btn" click="acceptFunction()">
                      <fa name="check"></fa>
                  </button>
          `
        })

        export class BtnSubmitComponent {
          @Output() clicked: EventEmitter<any> = new EventEmitter();
          cancelFunction(){
            this.clicked.emit("CANCELLED"); // Pass any payload as argument
          }
          acceptFunction{
            this.clicked.emit("ACCEPTED"); // Pass any payload as argument
          }
        }

父标记

<btn-submit (clicked)="onAddClicked($event)" [acceptFunction]='test'></btn-submit>

父 Typescript 函数

onAddClicked(event: any){
console.log(event); // Your payload is in 'event'
}