首页 > 解决方案 > 传递 ngSubmit 作为参考 Angular

问题描述

是否可以将 ngSubmit 函数作为参数传递?我创建了一个接收 Id 和 ngSubmit 函数名称的组件,但是如何将这个参数放在模板上?

我有一个名为验证表单的组件

验证-form.component.html

<form [id]="formId" method="post" novalidate [(ngSubmit)]="">
    <ng-content></ng-content>
</form>

我的 validation-form.component.ts 有

  @Input() formId: string;
  @Input() submit: string;

我像这样传递这个值

<validation-form formId="ResetPasswordForm" submit="resetPassword()">
</validation-form>

我想把@Input() 的值提交:字符串;到 (ngSubmit)。我怎样才能做到这一点?

标签: angulartypescriptangularjs-directiveangular7

解决方案


看起来您想要处理validationor submissionon parent component 而不是 child component validation-form

为此,您可以使用@Output装饰器。它将事件从孩子传播到父母。这是可以帮助您实现相同目标的代码。

验证-form.component.ts

  @Input() formId: string;
  @Input() submit: string;
  @Output() submit = new EventEmitter();

  public submit(){
     this.validate.emit(this.formId); //<-- you can pass the object if you need more info to pass.
  }

验证-form.component.html

<form [id]="formId" method="post" novalidate (ngSubmit)="submit()">
    <ng-content></ng-content>
</form>

父组件.html

<validation-form formId="ResetPasswordForm" (submit)="resetPassword($event)">
</validation-form>

父组件.ts

public resetPassword(formId){
  console.log("Form Id ", formId);
}

推荐阅读