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

Is it no longer possible to instantiate an object using the syntax <interface>{}?

There seems to be an issue with the code snippet below when run in the TypeScript playground: interface Person { name: string; age: number; } const makePerson= function(name : string, age : number) : Person { let obj = <Person>{} ...

Checking canActivate functionality in angular 2 using karma and jasmine: a guide

Looking to test the canActivate function in Angular 2 with TypeScript, Karma, and Jasmine. The code for the function is as follows: public canActivate(next: ActivatedRouteSnapshot, state: RouterStateSnapshot): Observable<boolean> { return t ...

What is the most efficient way to perform an inline property check and return a boolean value

Can someone help me with optimizing my TypeScript code for a function I have? function test(obj?: { someProperty: string}) { return obj && obj.someProperty; } Although WebStorm indicates that the return value should be a boolean, the TypeScript compil ...

Encountered an issue when trying to convert JSON into an array and loop through it in an HTML file using a

Currently, I am working on a project involving Angular where I am retrieving data from an API through a GET call. Specifically, one column's data is being converted from JSON to an array. However, when attempting to iterate over this array in the HTML ...

Instructions for enabling the touch slider feature in the Igx carousel component with Angular 6 or higher

Looking to enable the touch slider for Igx carousel using angular 6+? I am trying to implement the igx carousel for image sliding with reference from a stackblitz demo (https://stackblitz.com/edit/github-j6q6ad?file=src%2Fapp%2Fcarousel%2Fcarousel.compone ...

How to display the Y axis value on the category axis in a solid gauge using amcharts

My Code : <div id="chartdiv"></div> Styling : #chartdiv { width: 100%; height: 200px; } Script: am4core.useTheme(am4themes_animated); var chart = am4core.create("chartdiv", am4charts.RadarChart); chart.data = [{ ...

Create the Angular 6 service within the directory "e2e/app"

After upgrading my Angular 4 to 6, I attempted the following command: ng generate service security/security However, the service was generated under the "e2e/app" folder instead of the expected "src/app" location. Below is an excerpt from my angular.json ...

When emitting an event multiple times in Angular, an error may occur where properties of undefined are unable to be read, particularly in relation to the "

I am encountering an issue with my event binding on a button, specifically (click)="onStart()". The problem arises when the event this.numEmitter is emitted for the first time in setInterval, after which I receive the error message ERROR TypeError: Cannot ...

Is there a way to troubleshoot the issue pertaining to using routerLink in Angular version 17.2?

Currently working on a small app, but encountering an error with routerLink in the console. I am new to angular and seeking help. ✘ [ERROR] NG8002: Can't bind to 'routerLink' since it isn't a known property of 'a'. Here is ...

Guide on defining a data type for the response payload in a Next.js route controller

interface DefaultResponse<T> { success: boolean; message?: string; user?: T; } export async function POST(req: Request) { const body: Pick<User, 'email' | 'password'> = await req.json(); const user = await prisma ...

"Troubleshooting Angular 2 Directives That Cause Errors

Hey there, I'm currently working on understanding ANGULAR 2 routing, but I've encountered an error that's causing some trouble. Here's the issue I'm facing: app/app.component.ts(7,12): error TS2345: Argument of type '{ s ...

The symbol 'submitted' has not been declared

I have been working on implementing client-side validation in Angular using ReactiveForms. I encountered an error stating "Identifier 'submitted' is not defined. 'FormGroup' does not contain such a member" on this line: <div *ngIf=&q ...

Conceal the Angular Material toolbar (top navigation bar) automatically when scrolling downwards

In my Angular application, the main navigation consists of a standard toolbar positioned at the top of the page. My goal is to have this navigation bar smoothly scroll up with the user as they scroll down, and then reappear when they scroll back up. I at ...

What is the best way to create a distinct slug using TypeScript and mongoose?

After scouring through numerous modules, I couldn't find one that worked with TypeScript, including mongoose-slug-generator and mongoose-slug-plugin. ...

When using the `const { }` syntax, which attribute is made accessible to the external

I am using the ngrx store as a reference by following this example: https://stackblitz.com/edit/angular-multiple-entities-in-same-state?file=src%2Fapp%2Fstate%2Freducers%2Fexample.reducer.ts Within the code in example.reducer.ts, there is this snippet: ...

Who is responsible for ensuring that the data has been successfully stored in the state?

As I work on utilizing SSR with TransferState, a question arises about the assurance of data storage in the transferState. This concern stems from the asynchronous nature of http.get, which may result in content delivery to the client before the desired ...

Angular's focus function poses certain challenges that need to be addressed

I am seeking assistance as a new programmer facing a beginner's challenge. I have two inputs and I would like to enter a series of numbers in the first input (DO) and have them automatically populate in the second input (communal code). Inputs: http ...

Ionic Troubleshoot: Issue with Reading Property

Encountering an error: A TypeError occurs: Cannot Read Property of "username" of Undefined The HTML code responsible for the error is as follows: <ion-content padding style="text-align: center; margin-top: 35px"> <form (ngSubmit)="logFor ...

Using Default Parameters in the ngrx getWithQuery() Function

Curiosity strikes me on how to send the default data already present in getWithQuery(), just like this: @Injectable({providedIn: 'root'}) export class CompaniesDataService extends DefaultDataService<Company> { private readonly _URL: str ...

Utilizing Eithers to effectively manage errors as they propagate through the call chain

I'm delving into functional programming and exploring different ways to handle errors beyond the traditional try/catch method. One concept that has caught my attention is the Either monad in various programming languages. I've been experimenting ...