By Roxy'Pro


2018-12-06 14:58:22 8 Comments

I'm working on Angular app, its basically small app which is displaying spots for cars, cars could be on different regions (like in garage, outside of garage)..

And when I click on spot it's changing colour to red, like it's taken, but I can not see it until I close window and come back again.

Here are 2 components,

one cars-spot-list is parent component, and car-spot itself is child component as it's part of list.

So what I want to do, is when I click on car spot I'm updating my database as that spot is taken and I would like to call my method again getCarSpotsByArea() but it's located in parent-component, so my question is how can I call parent method from a child component?

I might move it to a service, but I would like to avoid that.

Here is how it looks:

enter image description here

My code:

When I click on child component car-spot for example Spot 1, this happened:

 onClick(carSpot: CarSpot) {
        this._carSpotService.changeCarSpotState(carSpot).subscribe(
          // Successful responses call the first callback.
          () => {
           // CALL AGAIN SOMEHOW METHOD FROM A PARENT TO REFRESH MY VIEW 
           // for example: getCarSpotsByArea(carSpot.areaId);
          },
          (err: HttpErrorResponse) => {
            if (err.error instanceof Error) {
              console.log('An error occurred:', err.error.message);
            } else {
              console.log(`Backend returned code ${err.status}, body was: ${err.error}`);
            }
          }
        );
      };
    }

Parent component: car-spot-list component

    getCarSpotsByArea(areaId: string) {
    this._carSpotService.getCarSpotsByAreaId(areaId)
      .subscribe(
      data => {
        this.carSpots = data;
      },
      // Errors will call this callback instead:
      (err: HttpErrorResponse) => {
        if (err.error instanceof Error) {
          // A client-side or network error occurred. Handle it accordingly.
          console.log('An error occurred:', err.error.message);
        } else {
          // The backend returned an unsuccessful response code.
          // The response body may contain clues as to what went wrong,
          console.log(`Backend returned code ${err.status}, body was: ${JSON.stringify(err.error)}`);
        }
      }
    );

2 comments

@Roxy'Pro 2018-12-06 15:26:04

What I did:

In my child component I've created a property which will emit value that I need:

@Output() onUpdateCarSpot = new EventEmitter<string>();


onClick(carSpot: CarSpot) {
    this._carSpotService.changeCarSpotState(carSpot).subscribe(
      // Successful responses call the first callback.
      () => {
       // Here is the place where I needed to call parent method so here
       // on success callback I've emitted value
          this.onUpdateCarSpot(carSpot.areaId);
      },
      (err: HttpErrorResponse) => {
        if (err.error instanceof Error) {
          console.log('An error occurred:', err.error.message);
        } else {
          console.log(`Backend returned code ${err.status}, body was: ${err.error}`);
        }
      }
    );
  };
}

And in parent component car-spot-list.component.html I did next ( is part of ) :

<car-spot (onUpdateCarSpot)="getCarSpotsByArea($event)"></car-spot>

I've added an (onUpdateCarSpot) which is acctually name of my Output event emitter from my Child component, and I've simply told:

Okay, when I emit something (it's on callback in a child component), call a method called getCarSpotsByArea and I've passed/emitted areaId because my parent's method getCarSpotsByArea accepts and areaId as a argument and that's it!

@ABOS 2018-12-06 18:32:09

In addition to EventEmitter as mentioned above, there are 2 other ways to call parent component from child components

1) Inject parent component into child component

export class ChildComponent  {
  constructor(private parent: ParentComponent) {

  } 

  callParentMethod() {
    this.parent.methodHandler();
  }
}

2) If you have control over ParentComponent, you can use exportAs:

@Component({
  ...
  exportAs: 'parent'
})
export class ParentComponent  {
  ...
}

export class ChildComponent  {
  @Input() handler: Function;
  ... 
  callParentMethod() {
    this.handler();
  }
}  

In Html, you can reference it as:

<parent #p="parent">
  <child [handler]="p.methodHandler"></child>
</parent>

Related Questions

Sponsored Content

7 Answered Questions

[SOLVED] Call child method from parent

  • 2016-06-21 16:34:48
  • Evo SL
  • 124057 View
  • 204 Score
  • 7 Answer
  • Tags:   javascript reactjs

32 Answered Questions

1 Answered Questions

How to destroy a child component inside a parent component

1 Answered Questions

41 Answered Questions

[SOLVED] How can I create a two dimensional array in JavaScript?

6 Answered Questions

[SOLVED] How can I use a not:first-child selector?

1 Answered Questions

[SOLVED] EventEmitter not emitted when called in subscribe

1 Answered Questions

1 Answered Questions

[SOLVED] call parent function from child of child component react

  • 2017-05-10 06:25:15
  • Daniel Gustafsson
  • 1683 View
  • 1 Score
  • 1 Answer
  • Tags:   javascript reactjs

1 Answered Questions

[SOLVED] How can my child component update my parent component in React JS?

Sponsored Content