【问题标题】:How to use @Output in angular 6 to emit an Array of Objects?如何在角度 6 中使用 @Output 来发出对象数组?
【发布时间】:2018-12-11 10:29:30
【问题描述】:

我有一个包含多个输入字段的表单,我想在使用@Input 和@Output 单击提交按钮时输出填写在表单中的数据以显示在我的页面中 在我的 form-template.component.ts-

export class FormTemplateComponent implements OnInit, AfterViewInit {

model: any = {};
task: Array<any> = [];
@Output() valueChange = new EventEmitter<any>();

onSubmit() {
  this.task.push({Name: this.model.name, Phone: this.model.phone, 
  Email: this.model.email, Password: this.model.password});
  this.valueChange.emit(this.task);
}

现在在我的 app.component.html 中添加了这个

<app-form-output-io (valueChange)="displayArray($event)"></app-form-output-io>

现在,在 app.component.ts 中定义 displayArray($event)

outputTableArray: any=[];
displayArray(theArray){
  this.outputTableArray=theArray;
  console.log(theArray);
  console.log('the array');
}

所以,什么都没有发生!

【问题讨论】:

  • app-form-output-ioFormTemplateComponent 的选择器?
  • 您的消息是空的还是根本没有消息?如果没有消息,您是否检查过您的提交事件?
  • @Output() valueChange = new EventEmitter();
  • @Eliseo 可以,谢谢。

标签: angular typescript angular6 angular-components angular-forms


【解决方案1】:

也许,您应该考虑输入您的模型,并将其与您的事件一起返回。

export interface MyModel {
  name: string,
  phone: string,
  email: string,
  password: string
}

export class FormTemplateComponent implements OnInit, AfterViewInit {

model: MyModel = {};
@Output() valueChange = new EventEmitter<MyModel>();

onSubmit() {
  this.valueChange.emit(this.model);
}

您也可以使用 ReactiveForms 并直接返回表单模型。

【讨论】:

  • 您好,如果父组件中的提交按钮和子组件中的@Output,您有什么想法吗?
  • 您能否提供更多详细信息,我不确定是否理解。您想从父组件调用子组件内的方法吗?是这样吗?
  • 你能说得更具体些吗@James
【解决方案2】:

我遇到了类似的问题,但对象数组是双向绑定的。

  @Input()
  services: Service[];

  @Output()
  servicesChange: EventEmitter<Service[]> = new EventEmitter<Service[]>();

在父组件中我有一个单独的下拉菜单

<p-dropdown [options]="services"> </p-dropdown>

还有一个Create New Service 按钮可以打开我的子组件,

<app-create-service [(services)]="services"></app-create-service>

我可以在其中创建一个新服务。即使我发出更新的数组,

      this.services.push(newServiceObject);
      this.servicesChange.emit(this.services);

我的下拉菜单没有更新。 EventEmitter 适用于简单数据类型,但不适用于对象。我认为这是因为指向修改列表的指针没有改变,所以我的解决方案是将我的数组复制到另一个数组中:

      this.services.push(newServiceObject);
      this.servicesChange.emit([...this.services]);

【讨论】:

    猜你喜欢
    • 2019-08-24
    • 1970-01-01
    • 1970-01-01
    • 2019-04-27
    • 1970-01-01
    • 2020-05-13
    • 2019-05-07
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多