Refreshing a variable during component initialization

In the Event 1 component, there is a variable that holds a string from another variable in the data.service. I want to update the data.service string to 'Event 2' when the Event 2 component loads.

I have attempted to implement the following code without success. I have tried calling it in ngAfterViewInit and from a button as well.

Event 1 Component:

public Title = this.dataservice.Title;

Data.service:

public Title = "Event 1";

Event 2 Component:

changeTitle(){
      this.dataService.Title = 'Event 2';
      console.log("CHANGE TITLE");
    }


    ngAfterViewInit(): void {
       this.changeTitle();
    }

    

Answer №1

Within the dataService.ts file:

import { EventEmitter } from '@angular/core';
export class DataService {
    updatedTitle = new EventEmitter<string>();
    onUpdateTitle(title) { // Invoke this method on button click
       // Can be saved in a variable
       this.updatedTitle.emit(title);
    }
}

In the component.ts file:

export class Component implements OnInit {
    title: string;
    ngOnInit() {
        this.dataService.updatedTitle.subscribe((res) => { 
            this.title = res;
        });
    }
}

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

Issue R10 (Start-up delay) -> Failure of web application to connect to $PORT in the given 60 seconds after being launched (Angular)

I am currently in the process of building an Angular 7 application and attempting to connect it to Heroku (I am fairly new to using Heroku). Upon trying to run the application on Heroku, I encountered the following error: https://i.stack.imgur.com/ySmJw.p ...

Improving mat-expansion-panel ngFor in AngularEnhancing the performance of mat-exp

I'm currently working on populating a mat-accordion with mat-expansion-panels using the code below: <mat-accordion> <mat-expansion-panel *ngFor="let item of items; trackBy: trackByFunction; let i = index" hideToggle="tr ...

What is the process for setting up SSL for Angular e2e testing?

I'm working on an Angular sample project that includes end-to-end tests focusing on OAuth2 and OIDC flows. I've noticed that the behavior of browsers varies when SSL/TLS is enabled or disabled. To ensure consistency, I would like to run my end-to ...

Having trouble correctly initializing RequestOptionsArgs for a POST request in the service function

Recently, I have been working with Angular 6 and decided to follow a helpful video tutorial on image submissions (link to the video). My goal is to track the progress of the form submission in order to display the percentage of the uploaded file. In my c ...

Issues with Angular 2 loading properly on Internet Explorer 11

We are currently running an Asp.net MVC 5 web application integrated with Angular 2. The application functions smoothly on Chrome, Firefox, and Edge browsers, but encounters loading issues on IE 11, displaying the error illustrated in the image below: ht ...

angular 7 - Issue with displaying toastr messages using ngx-toastr

I've been working on a web app using Angular 7 and I wanted to implement ngx-toastr for user notifications. However, I'm encountering issues as the toast notifications are not displaying correctly. Instead of the toast popping up when triggered, ...

Angular application making a POST request to a Spring REST API

I have developed a RESTful API using Spring Boot and a client application using Angular 4. Both applications are currently running locally. When testing the POST method with Postman, it functions correctly. However, when attempting to make a POST request f ...

Tips for utilizing ng class within a loop

Having some trouble with my template that loops through a JSON file using json server. The issue I'm facing is related to correctly applying ng class when clicking on icons. Currently, when I click on an icon, it adds a SCSS class but applies it to al ...

Creating JPEG images with specified dimensions. How can you add W x H sizing to an image?

I have been searching for a Deno/TypeScript code snippet that can create basic images with dimensions embedded on them. I have provided an example of the code below, which generates images in JPEG format, base64, and dataURL. The code works by adding RGB ...

Typedoc: only export contents from a particular file are documented

Currently, I am working on developing two npm packages: https://github.com/euberdeveloper/mongo-scanner https://github.com/euberdeveloper/mongo-cleaner My goal is to create documentation for these packages using Typedoc. The main file is index.js p ...

Step-by-step guide on installing both Angular and Nodejs within a single folder

I'm diving into the world of NodeJs and Angular, and I recently created a simple NodeJS application following instructions from this link. However, I encountered an issue when trying to install Angular alongside NodeJS. After running ng new angular-cr ...

I am having trouble figuring out the issue with the state and how to properly implement it in Typescript

I am having difficulties sending emails using Nodemailer, TypeScript, and NextJS. The contact.tsx file within the state component is causing errors when using setform. As a beginner in TypeScript, I have been unable to find a solution to this issue. Any he ...

Retrieving raw HTML content using Angular's http.get() method

Currently working on a project where I need to load data dynamically from a website without the use of an API. Is there a way in Angular to utilize http.get in order to fetch the entire website as raw HTML, allowing me to extract specific information? Any ...

The type 'Observable<HttpEvent<DeviceList>>' cannot be assigned to the type 'Observable<DeviceList>'

// FUNCTION TO RETRIEVE DEVICE LIST fetchDeviceList(): Observable < DeviceList > { this.setToken(); return this.http.get<DeviceList>(this.api_url + '/devices', this.httpOptions1) .retry(2); } I am facing a challenge in this p ...

Trouble encountered while attempting to install ng2-bootstrap within my Angular 2 project

I've been attempting to integrate ng-bootstrap into my Angular 2 application for dropdown functionality. However, I'm encountering the following error in the console: Console error Here is the snippet of my System.config.js code: System.config. ...

This marks my initial attempt at developing an Angular project using Git Bash, and the outcome is quite remarkable

I have a project named a4app that I am trying to create, but it seems to be taking around 10 minutes to finish and is showing errors. The messages displayed are quite odd, and I suspect there may be an issue with the setup. I have not yet used the app that ...

The functionality of an Angular application may be compromised if the necessary modules are not properly imported into

I've noticed some strange behavior in my code recently and I can't figure out where it's originating from. In an effort to clean up my codebase, I decided to create separate modules for each component and a routing module to manage all the r ...

Utilizing separately generated elements from ngFor

I am currently working with an angular2 component that generates a list of chapters using an *ngFor= tag. However, I am facing an issue where I am unable to individually target these chapters in my ng2 component to highlight the selected chapter. I expecte ...

What is the reason behind NumberFormat only recognizing four numbers?

Encountering an issue with inputting values into a TextField embedded in NumberFormat. Only three numbers are accepted before the field resets. I aim to divide the value in the TextField by a format based on the selection made in the drop-down menu. For ex ...

Encountering errors after updating to Angular Material version 6.4.7

I recently updated my Angular/Material to version 6.4.7 in my Angular2 project, but now I am experiencing a number of errors. I suspect that this may be due to the fact that my Angular/CLI version is at 1.7.4. Is there a way for me to successfully integra ...