Share object between child-parent .ts components with @OutPut

Issue

I have two material dialog components. One is the parent, in this one by pressing a button you open the second one. The second one is the child and is basically a form. By submitting this form I create an object which should be sent to the parent component. I’ve been trying to use the @Output decorator with mild success. Take into account I’m only providing the needed code for sharing the data, both components are much more complex.

Child Component

@Component({
  selector: "wrapper-add-dev",
  templateUrl: "./wrapper-add-dev.html",
  styleUrls: ["./wrapper-add-dev.css"],
  providers: [DevizeService, ConfigService]
})

export class WrapperAddDevComponent implements OnInit {


@Output() wrapperOutput= new EventEmitter();


/**CODE THAT RETRIEVES THE REACTIVE FORM VALUE**/

///devize is the object i want to emit

  addWrapperToMetaDevize(devize) {
   this.wrapperOutput.emit(devize);

  }


}

Parent Component



@Component({
  selector: 'metadevize-add',
  templateUrl: './metadevize-add.html',
  styleUrls: ['./metadevize-add.css']
})

export class MetaDevizeAddComponent implements OnInit {


showWrapper(event){
//printing the device into the console
  console.log(event);
}


}

Parent HTML

<wrapper-add-dev (wrapperOutput)="showWrapper($event)"> </wrapper-add-dev>

The result is that the child’s form is being rendered into the parent’s template, and the devize object is printed. Because of this if I want to fill the form I need to do it in the parent’s template cause the child’s one is not rendered properly.

The ultimate goal is to be able to use the object within the parent’s typescript without rendering the child’s template. All examples online are oriented into rendering the message in parent’s template which isn’t what I really want to achieve. To be honest I find this way of sharing data by using html and typescript quite confusing.

I’ve also tried using a Save/Fetch shared service with no avail.

Solution

Finally used a much simpler approach. When opening the child component I created a subcribe service to an event emitter created on the child.

Parent

wrapperAddDevizeDialog() {
   this.isPopupOpened = true;
    const dialogRef = this.dialog.open(WrapperAddDevComponent, {
      data: {level: this.data.level+1}
    });

   //Subscription to Event Emitter
   dialogRef.componentInstance.onAdd.subscribe((result:any)=>{
      this.devizeWrapper=result;
      //I can use this.devizeWrapper as I want within the parent component.
    })


    dialogRef.afterClosed().subscribe(result => {
      this.isPopupOpened = false;
    });
  }


Child

  onAdd = new EventEmitter();

  addWrapperToMetaDevize(devize){

      this.wrapperDev=devize;

      this.onAdd.emit(devize);

  }

Answered By – Supersoaker

Answer Checked By – Clifford M. (AngularFixing Volunteer)

Leave a Reply

Your email address will not be published.