Search code examples
angulartypescriptangular6angular-componentsangular-forms

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!


Solution

  • 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.