1

我正在尝试使用带有事件发射器的单击事件绑定和@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)
  }

模型.ts

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

}
4

2 回答 2

3

根据您提供的代码,您似乎在这里重新分配了 EventEmitter;

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

如果您重新分配此变量,您将在下次提交表单时失去原始 EventEmitter 的范围。

于 2020-04-01T05:16:44.303 回答
0

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

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

于 2020-04-01T11:57:05.710 回答