【问题标题】:Angular how to fix emit is not a function with Event-emitterAngular 如何修复发射不是事件发射器的功能
【发布时间】:2020-07-12 19:13:10
【问题描述】:

我正在尝试使用带有事件发射器的 click 事件绑定和 @Output,以从不同的组件记录数据。 我需要一些我认为可能没有使用好方法的指导方针

contactform.component.html

 <form class="form-signin form" [formGroup]="kForm" (ngSubmit)="onSubmit($event)">

    <div class="form-label-group">
      <input type="email" id="inputName"  placeholder="Name" formControlName="name" #name>
      <label for="inputName">Name</label>
    </div> 

    <div class="form-label-group">
      <input type="email"  placeholder="Email address" formControlName="email" #email>
      <label for="inputEmail">Email address</label>
    </div>

    <div class="form-label-group">
      <input type="text"  class="form-control" placeholder="phone" formControlName="phone" #phone>
      <label for="inputPhone">Phone</label>
    </div>

    <div class="form-label-group">
        <input type="text"   placeholder="country" formControlName="country" #country>
        <label for="inputCountry">Country</label>
      </div>

    <button class="btn  btn-primary" type="submit" [disabled]="!kForm.valid" (click)="onSubmit(name.value, email.value, phone.value, country.value)">Submit</button>
</form>

contactform.component.ts

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

 @Output() onSave =  new EventEmitter<Contact>();  

onSubmit(value:Contact){ 
    this.onSave.emit(value) 
    this.onSave = this.kForm.value;
    // console.log('k',this.kForm.value);
    console.log('submitted', this.onSave)
  }

app.component.html

<contact-form (newItem)="addItem($event)"></contact-form>

app.component.ts

addItem(newItem:string){
    console.log(newItem)
  }

Model.ts

export interface Contact{
    name: string;
    email: string;
    phone: string;
    country: string;

}

【问题讨论】:

  • 只需删除 this.onSave = this.klloydForm.value,并在 this.onSave.emit(this.klloydForm.value) 上方的一行中,我想它会有所帮助
  • @NavruzbekNoraliev 确实很棒,但我可以在控制台中获取用户输入
  • console.log(value); console.log(this.klloydForm.value)
  • 这是真的,我被骗了,干得好 :)

标签: angular angular-event-emitter


【解决方案1】:

根据您提供的代码,您似乎在此处重新分配 EventEmitter;

onSubmit(value:Contact){ 
    this.onSave.emit(value) 
    this.onSave = this.klloydForm.value; <-------------------- Remove this
    console.log('submitted', this.klloydForm.value)
}

如果你重新分配这个变量,下次提交表单时你将失去原来 EventEmitter 的作用域。

【讨论】:

  • 太好了,我已经完成了,错误不再显示,但输入没有记录到控制台。你能帮忙吗
  • 尝试添加; console.log('提交', this.klloydForm.value)
【解决方案2】:

您已经在contactform.component.ts中创建了onSave的输出事件,因此您必须从组件调用相同的事件才能触发

&lt;contact-form (onSave)="addItem($event)"&gt;&lt;/contact-form&gt;

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2018-01-17
    • 1970-01-01
    • 1970-01-01
    • 2018-06-01
    • 2018-10-20
    • 2019-02-01
    • 1970-01-01
    相关资源
    最近更新 更多