Debadatta
Debadatta

Reputation: 1732

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

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-

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-form-output-io (valueChange)="displayArray($event)"></app-form-output-io>

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

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

So, nothing Comes up!

Upvotes: 4

Views: 24280

Answers (2)

Tavy
Tavy

Reputation: 871

I had a similar issue but with a 2-way-binding array of objects.

  @Input()
  services: Service[];

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

In the parent component I have a separate dropdown

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

and a Create New Service button that opens my child component,

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

in which I can create a new service. Even If I was emitting the updated array,

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

my dropdown wasn't updating. EventEmitter works with simple data types but not with objects. I think it's because the pointer to the modified list doesn't change, so my solution was to copy my array into another one:

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

Upvotes: 0

Thierry Falvo
Thierry Falvo

Reputation: 6290

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.

Upvotes: 2

Related Questions