typescript 如何在 angular 6 中使用@Output 来发出对象数组?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/51148973/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-10-21 05:30:42  来源:igfitidea点击:

How to use @Output in angular 6 to emit an Array of Objects?

angulartypescriptangular6angular-componentsangular-forms

提问by Debadatta

I have a Form Having Multiple Input Fields, I want to Output the data filled in the form to be shown in my Page on click of a submit button using @Input and @Output In my form-template.component.ts-

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

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);
}

Now added this in my app.component.html

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

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

Now, defining the displayArray($event) in app.component.ts

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

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

So, nothing Comes up!

所以,什么都没有出现!

采纳答案by Thierry Falvo

Maybe, you should consider to type your model, and return it with your event.

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

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);
}

You can also use ReactiveForms and return form model directly.

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