What is the role of @Output and EventEmitter in Ionic development?

I'm currently working on integrating Google Maps and Firebase database. My goal is to save my location in the Firebase database and transfer data using @Output and eventEmitter. However, I am facing an issue where pickedLocation has a value but this.locationPick does not get assigned a value. Can anyone assist me with this problem?

@Component({
  selector: 'app-location-picker',
  templateUrl: './location-picker.component.html',
  styleUrls: ['./location-picker.component.scss'],
})
export class LocationPickerComponent implements OnInit {
  @Output() public locationPick = new EventEmitter<PlaceLocation>();
  isLoading = false;
  selectedLocationImage: string;
  place: Place[];

  constructor(private modalCtrl: ModalController, private http: HttpClient) { }

  ngOnInit() {}

  onPickLocation() {
    this.modalCtrl.create({component: MapModalComponent}).then(modalEl => {
      modalEl.onDidDismiss().then(modalData => {
        if (!modalData.data) {
          return;
        }
        const pickedLocation: PlaceLocation = {
          lat: modalData.data.lat,
          lng: modalData.data.lng,
          address: null,
          staticMapImageUrl: null
        };
        this.isLoading = true;
        this.getAddress(modalData.data.lat, modalData.data.lng)
        .pipe(switchMap(address => {
          pickedLocation.address = address;
          return of(this.getMapImage(pickedLocation.lat, pickedLocation.lng, 14));
        })).subscribe(staticMapImageUrl => {
          pickedLocation.staticMapImageUrl = staticMapImageUrl;
          this.selectedLocationImage = staticMapImageUrl;
          this.isLoading = false;
          this.locationPick.emit(pickedLocation);
          console.log(pickedLocation);
        });
      });
      modalEl.present();
    });
  }

  private getAddress(lat: number, lng: number) {
    return this.http
    .get<any>(
      `https://maps.googleapis.com/maps/api/geocode/json?latlng=${lat},${lng}&key=${environment.googleMapsAPIKey}`
      )
      .pipe(
        map(geoData => {
          if (!geoData || !geoData.results || geoData.results.length === 0) {
            return null;
          }
          return geoData.results[0].formatted_address;
      }));
  }

  private getMapImage(lat: number, lng: number, zoom: number) {
    return `https://maps.googleapis.com/maps/api/staticmap?center=${lat},${lng}&zoom=${zoom}&size=500x300&maptype=roadmap
    &markers=color:red%7Clabel:Place%7C${lat},${lng}
    &key=${environment.googleMapsAPIKey}`;
  }
}

The issue I'm facing is that while console.log(pickedLocation); outputs the expected URL, console.log(this.locationPick); displays an empty result.

    EventEmitter {_isScalar: false, observers: Array(1), closed: false, isStopped: false, hasError: false, …}
closed: false
hasError: false
isStopped: false
observers: [Subscriber]
thrownError: null
__isAsync: false
_isScalar: false
__proto__: Subject

Answer №1

To implement the functionality of LocationPickerComponent, insert the code below into the HTML file of the Parent component:

<app-location-picker (locationPick)="locationPicked($event)"></app-location-picker>

In the TypeScript file of the parent component, add the following function to receive the value:

locationPicked(value) {
  console.log(value)
}

If you want to explore different techniques for sharing data between components in Angular, check out this informative article:

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Connecting a Database with NestJS and TypeORM: A step-by-step guide to establish a connection with TypeORM and ensure easy access to

Could someone please explain how to create a DB instance using TypeORM? I want it to be accessible like this service, but the Connection class is deprecated. import { Inject, Injectable } from '@nestjs/common'; import { Connection, Repository } ...

Identifying the end of a tree traversal using RxJS

I've hit a roadblock in my design process involving RxJS. Despite dedicating considerable time to studying the documentation, I haven't been able to find a solution. If anyone can offer some guidance... Currently, I'm navigating through a t ...

Ways to retrieve a Class Level Variable within the onCellValueChanged function in agGrid

Exploring Angular with Typescript for the first time. I'm trying to access Class Level Variables within the onCellValueChanged event of agGrid, but encountering the following error: Cannot read property 'updateDict' of undefined Here&apo ...

Discover the Prisma findMany method for implementing tanstack react table functionality

I'm looking to build a table (using tanstack table) populated with data fetched from Prisma.findMany. Let's suppose I have a User model: model User { id Int @id @default(autoincrement()) name String age String email String } Now, in my p ...

Rect cannot be resized using mouse events

I am currently working on resizing the rectangle inside the SVG using mouse events. To achieve this, I have created another circle shape at the right bottom edge of the rectangle and implemented resize events on that shape. However, I'm facing an issu ...

Adding JSON content to a form for editing functionality within an Angular 8 CRUD application

I am currently working on building a Single Page Application using Angular 8 for the frontend and Laravel for the backend. I have been able to successfully pass data to the backend via JWT, and everything is functioning as expected. The application follows ...

Is it just me, or does the this.router.subscribe method no longer exist in Angular 2's @angular/router library?

I'm experiencing an issue in Angular 2 with the library @angular/router. It appears that the method this.router.subscribe no longer exists. Previously, this code worked fine on an older version of the router that has since been deprecated. Does anyon ...

Leveraging symbols as object key type in TypeScript

I am attempting to create an object with a symbol as the key type, following MDN's guidance: A symbol value may be used as an identifier for object properties [...] However, when trying to use it as the key property type: type obj = { [key: s ...

Exploring Angular observables: Tips for gathering specific fields from a nested array within an object into a new array

I am working on parsing a JSON object and extracting specific fields to create their own array. My goal is to loop through the provided object and gather the 'appSupportedId' values into a separate array. An issue has arisen, leading to an ERRO ...

Verify whether an object possesses all the attributes of a class in TypeScript

Within my typescript code, I have a class called abc: export class ABC{ public a : any; public b : any; public c? : any; public d? : any; } In one of my functions, I receive an input which is represented as data:any. My goal is to verify i ...

Creating a WebExtension using Angular and TypeScript

I am currently working on creating a WebExtension using Angular and Ionic. The extension successfully loads the application and enables communication between Content Script and Background Script. However, I am facing an issue where the TypeScript code is n ...

"Unfortunately, Azure Web Static Apps do not have the capability to access .env files that are prefixed with NEXT

Suppose I have an .env file set up like this: NEXT_PUBLIC_API_BASE_PATH = value1 While this .env is functioning correctly in my local environment, once deployed to Azure Web Static Apps and added to the configurationhttps://i.sstatic.net/eqiYn.png My app ...

Why is it necessary for me to manually include and configure all d3.js dependencies in the SystemJS config file?

Currently, I am utilizing the systemjs.config.js file for an Application built on Angular5.x. To implement DAG charts in the application, I installed npm install --save @swimlane/ngx-graph and npm install --save @swimlane/ngx-charts. I have set up a comp ...

Tips for transferring the clicked value to the next page

Recently, I started working with Ionic and developed an application using it. Now, I am facing a challenge where I need to pass the value from the first page to the second page. To illustrate this more clearly, I have attached two photos. Here is the imag ...

Ensure that all content is completely loaded before displaying it using Angular 2

As an Angular developer, I am facing a challenge in my component where I am generating an image through a service HTTP call. Unfortunately, the image generation process takes longer than the site load time, causing the image to not appear immediately on th ...

Triggering JSON schema validation event in React's Monaco Editor

I am interested in implementing custom JSON schema validation in my Monaco editor setup. Here is the current configuration: <MonacoEditor language="json" value={jsonValue} editorWillMount={(monaco) => { monaco.languages.json.jsonD ...

Why can't a TypeScript string be assigned to a union type of string literals?

I have defined a type called Direction, which is a union of the strings 'LEFT' and 'RIGHT'. However, TypeScript (tsc) is giving me an error when I try to assign a 'LEFT' string to it. Here's the code snippet: type Directi ...

Updating Angular 9 values using a fixed object

I am dealing with a patch value here where I simply pass an object to it. this.formPesquisar.controls['daniloTeste'].patchValue(this.dadosVisualizar.daniloTeste); However, I would like to pass a static object instead, something like: this.formPe ...

Can you explain the distinction between String[] and [String] in TypeScript?

Can you explain the distinction between String[] and [String] in typescript? Which option would be more advantageous to use? ...

Obtain abbreviated names for the days of the week starting from Monday to Sunday using JavaScript

Is there a way to retrieve the abbreviated names of each day of the week in JavaScript, starting from Monday through Sunday? ...