Angular2 app fails to update after emitting an event

I need help with a child component responsible for updating phone numbers on a webpage. The goal is for the application to automatically display the changed phone number once the user hits the 'save' button.

Here's a visual of how the application should look: https://i.sstatic.net/lLwW5.png

And here's the popup where users can input a new phone number: https://i.sstatic.net/cfUa7.png

The issue I'm facing is that even after hitting the save button in the popup, the application fails to update the phone number immediately. It only updates the number when I manually refresh the page. Can anyone guide me on how to resolve this?

editPhone.component (Popup)

@Output() phoneChanged = new EventEmitter<string>();
constructor(private _http: HttpClient, private _phone: PhoneService){}

    //Function triggered upon clicking the 'Save' button
    savePhone(patientOrder: PatientOrder, phoneText: string){
            this._phone.patientId = patientOrder.patientId;

            return this._http.post('service', this._phone).subscribe((result:any) => {
                this._phone.phoneText = result.phoneNumber;
                this.phoneChanged.emit(this._phone.phoneText);
            });
        }

view.component (Application displaying the updated phone number)

 phoneNumber: string = "";
    phoneChanged(phone: string){
    //I can't seem to reach this point. Despite no errors, the console isn't logging anything.
            console.log(phone);
        }

view.html (Template)

<new-orders>
<div (phoneChanged)="phoneChanged($event)">{{phoneNumber}}</div>
</new-orders>

To avoid unnecessary questions, let it be known that everything in my application works fine except for this specific part that needs fixing.

Answer №1

The specified div is not the edit phone component, therefore it is not triggering the event you are attempting to bind to. It's rather surprising that this does not result in an error during compilation.

If you want to achieve this, you should modify it as follows:

<edit-phone (phoneChanged)="phoneChanged($event)"></edit-phone>

In this way, you will be binding to the event on the component responsible for emitting the event. However, this approach only works if the edit-phone component is a direct child of the component where the phone number is displayed. If they are not directly related like siblings or cousins, then utilizing a shared service pattern would be more appropriate.

Answer №2

The code you provided indicates that view.component is not the parent of editPhone.component, preventing it from listening for @output.

An updated HTML structure would resemble:

<view-component>
    // Insert MARKUP here
    <edit-phone-component (phoneChanged)="phoneChanged($event)"></edit-phone-component>
</view-component>

You may also need to assign an @Input() with the current value to the edit component.

An adjusted version could appear as follows:

<view-component>
    // Insert MARKUP here
    <edit-phone-component 
    [phoneNumber]=phoneNumber
    (phoneChanged)="phoneChanged($event)"></edit-phone-component>
</view-component>

For the EditPhoneComponent:

export class EditPhoneComponent {
    @Input() phoneNumber: string;
    @Output() phoneChanged = new EventEmitter<string>();

    // Other methods and constructor go here

    savePhone(patientOrder: PatientOrder, phoneText: string){
      // Save logic goes here
      this.phoneChanged.emit(this._phone.phoneText);
    }
}

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

Utilizing TypeScript in conjunction with Vue and the property decorator to assign default values to props

Hey there! I'm currently dealing with a property that looks like this, but encountering a type error when trying to translate text using i18n @Prop({ default: function() { return [ { > text: this.$t('wawi_id'), align: ...

Exploring the behavior of control flow in Typescript

I am a beginner when it comes to JS, TS, and Angular, and I have encountered an issue with an Angular component that I am working on: export class AdminProductsMenuComponent implements OnInit{ constructor(private productService: ProductService, ...

Using Angular 4 to monitor changes in two-way binding properties

Recently, I developed a unique toggle-sorting component that examines if the current sorting parameters align with its sorting slug and manages clicks to reflect any changes. // toggle-sorting.component.ts @Input() sortingSlug: string; @Input() currSorti ...

Use leaflet.js in next js to conceal the remainder of the map surrounding the country

I'm currently facing an issue and would appreciate some assistance. My objective is to display only the map of Cameroon while hiding the other maps. I am utilizing Leaflet in conjunction with Next.js to showcase the map. I came across a helpful page R ...

Vercel seems to be having trouble detecting TypeScript or the "@types/react" package when deploying a Next.js project

Suddenly, my deployment of Next.js to Vercel has hit a snag after the latest update and is now giving me trouble for not having @types/react AND typescript installed. Seems like you're attempting to utilize TypeScript but are missing essential package ...

Utilizing Angular's Dependency Injection to Provide Services to External Libraries

I'm currently developing an NPM package that enhances the functionalities of Material Datatable. One standout feature is the ability to specify a method that will be triggered when a user clicks on a specific cell. Here is how the property is defined ...

API response containing JSON data is not being displayed properly in the webdatarocks angular component

I can't seem to figure out how to properly display the JSON formatted data returned by a REST API using Angular. Any suggestions on how to accomplish this? Here's what I've been attempting to do - fetchData() { this.service.fetchData().s ...

Potential null object in React/TypeScript

Encountering a persistent error here - while the code functions smoothly in plain react, it consistently throws an error in typescript stating "Object is possibly null". Attempts to resolve with "!" have proved futile. Another error logged reads as follow ...

Typescript error: RequestInit not properly initialized

I'm encountering an issue while using fetch to call an API in a typescript file. The browser is throwing an error stating that const configInit must be initialized, even though I believe it is already. Any suggestions on how to resolve this? Thank you ...

Using Angular's FormControl with a Pipe

Trying to manipulate the value of an <input> using a pipe and display the modified value in a <paragraph> has proven to be quite challenging. Despite various attempts and thorough research, I have not been able to achieve the desired functional ...

Encountering error codes TS1005 and TS1109 while trying to run an Angular 6 project

Having difficulty starting my Angular 6 app due to this specific error. Is there a solution available? ERROR in node_modules/rxjs/internal/types.d.ts(81,44): error TS1005: ';' expected. node_modules/rxjs/internal/types.d.ts(81,74): error TS1005: ...

Can Autocomplete in Angular4+ support multiple selection options?

I am trying to implement a multi-selection feature on filtered items using an autocomplete function. I found inspiration from this tutorial and attempted the following code: The component : <form class="example-form"> <mat-form-field class=" ...

The InAppPurchase Plugin in Cordova is throwing the error message "Encountered an error: Cannot access the 'getProducts' property as it is undefined."

Currently, I am utilizing the cordova in-app-purchase plugin for my application. However, I am encountering an error that reads "ERROR TypeError: Cannot read property 'getProducts' of undefined" The .ts file appears as follows: window['plu ...

Mismatch between generic types

When working with this code, I encounter a syntax error at m1 and m2. The error message states: Type 'T' is not assignable to Type 'boolean' or Type 'T' is not assignable to Type 'string' interface customMethod { ...

Is there a way to consolidate two interface types while combining the overlapping properties into a union type?

Is there a way to create a type alias, Combine<A, B>, that can merge properties of any two interfaces, A and B, by combining their property types using union? Let's consider the following two interfaces as an example: interface Interface1 { t ...

What is the best way to assign JSON values to my class property?

I've been working on a weather application that showcases the current weather of 5 different cities. By clicking on each city, users can access a detailed view displaying the 5-day forecast for that particular location. Currently, I have defined a we ...

The error message, "Property 'message' is not found on type 'ErrorRequestHandler<ParamsDictionary, any, any, ParsedQs, Record<string, any>>.ts(2339)", indicates that the requested property is not present in the specified type

Hello there! Recently, I implemented a custom error handling middleware in my Node.js TypeScript application. However, I encountered an issue where it is showing an error stating that 'message' does not exist on type 'ErrorRequestHandler&apo ...

Utilizing Typescript for constructor parameter assignments

Within my codebase, there exists an interface: export interface IFieldValue { name: string; value: string; } This interface is implemented by a class named Person: class Person implements IFieldValue{ name: string; value: string; const ...

Angular - the ngFor directive causing function to be executed repeatedly

I need help with a template: <mat-card *ngFor="let cargo of cargos" class="cont-mat"> ... <mat-checkbox *ngFor="let truck of (retrievingTrucksByUserIdAndRules(cargo.id) | async)" formControlName="truckId" ...

I'm looking for ways to incorporate TypeScript definition files (.d.ts) into my AngularJS application without using the reference path. Can anyone provide

I'm interested in leveraging .d.ts files for enhanced intellisense while coding in JavaScript with VScode. Take, for instance, a scenario where I have an Angular JS file called comments.js. Within comments.js, I aim to access the type definitions prov ...