``Changing the value of a class variable in Angular 2 does not result in the

I am facing an issue with a component that contains a variable called myName

export class ConversationComponent implements OnInit {
  private myName: string;

  showNames(name)
  {
    this.myName=name;
  }
}

The value is assigned using the showNames() method, and it should be displayed as follows:

<h4>{{MyName}}</h4>

However, I noticed that when the value of the variable is changed, it is not reflected in the HTML view.

Below is an excerpt from my Service:

import { Injectable } from '@angular/core'; 
import { ConversationComponent } from './conversation/conversation.component'; 

@Injectable() export class ChatingService { 

  constructor(private Conversation:ConversationComponent) { } 

  setValue(val) { 
    this.Conversation.showNames(this.myValue); 
  } 
}

Answer №1

Attempting to inject a component into a service has proven ineffective. It appears that a different method is required in this scenario. It is possible that the component instance being injected is not directly associated with the component displayed on the page.

Answer №2

Give this a try:

@Component(...)
export class ChatComponent implements OnInit {
  private userName: string;

  constructor(private apiService: ApiService) {}

  ngOnInit() {
    this.displayUserName(this.apiService.getUsername());
  }

  displayUserName(name) {
    this.userName = name;
  }
}

In the code above, ApiService is the injectable service being used.

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

Tips for customizing labels for boolean filters in DevExtreme data grid

We are looking to change the filter options in the status field (last row) from true/false to Active/Inactive. While there is a coding method to achieve this, we are struggling as we are using a table template. It seems like it should be a simple task but ...

Polling with RxJs, handling errors, and resetting retryCount with retryWhen

I am currently working on setting up a polling strategy that functions as follows: Retrieve data from the server every X seconds If the request fails, show an error message: "Error receiving data, retry attempt N°"... And retry every X seconds for a maxi ...

React: a versatile and type-specific onChange() function

After adding as HTMLInputElement, the error message of Property 'checked' does not exist on type 'EventTarget & (HTMLInputElement | HTMLTextAreaElement)' is resolved. However, I find it interesting that TypeScript doesn't autom ...

The reload button retains functionality while being present within an Angular2 form, allowing for a seamless user experience. The

After some observation, I have realized that when a button is placed inside a form but has no connection or function related to the form, such as a back or cancel button, it unexpectedly reloads the entire page. For instance, let's consider having ...

TS fails to recognize any additional properties added to the constant object

When working on a function that should return an object with properties 'a' and 'b', I am defining the object first and then adding values to it later: const result = {}; result.a = 1; result.b = 2; return result; However, TypeScript i ...

Converting Venn diagram code from JavaScript <script> tags to Angular 2: A step-by-step guide

I am struggling to incorporate a Venn diagram into my Angular 2+ project. I followed the code sample provided at - http://jsfiddle.net/johnpham92/h04sknus/ To begin, I executed the following command - npm install venn.js Then I proceeded with impl ...

react-i18next: issues with translating strings

I encountered a frustrating issue with the react-i18next library. Despite my efforts, I was unable to successfully translate the strings in my application. The relevant code looked like this: App.tsx: import i18n from 'i18next'; import { initR ...

Is it possible to make the 'keyof' property optional?

Illustrate an interface in the following way interface Properties { apple?: string banana?: string cherry?: string date: string } Executing this code works as expected type Sample1 = { [P in keyof Properties]: Properties[P] } const s1: Sample1 ...

What should I do when dealing with multiple submit buttons in NextJS?

How can I differentiate between two submit buttons in a form component created in Next.js? I'm struggling to determine which button was pressed and need help resolving this issue. import React from "react"; const LoginPage = () => { as ...

Issue with importing MomentJS globally in TypeScript

When it comes to defining global external modules in TypeScript, there is a useful option available. For instance, if you have jQuery library loaded externally, you can set up a global definition without having to include its duplicate in the TypeScript bu ...

How can you alter the background color of a Material UI select component when it is selected?

I am attempting to modify the background color of a select element from material ui when it is selected. To help illustrate, I have provided an image that displays how it looks when not selected and selected: Select Currently, there is a large gray backgr ...

Displaying the grid ID outside of a card in Angular while using Bootstrap 4

Utilizing the core ui template in my Angular project with Bootstrap 4. Check out the page <div class="animated fadeIn"> <div class="row"> <div class="col-sm-12"> <div class="ca ...

Back up your Firestore data automatically using scheduled cron jobs!

Recently, I utilized the firestore-backup-restore tool for backing up Firestore data and it worked seamlessly. However, I am unsure how to schedule this process using cron jobs or a similar method. As someone with no prior experience in utilizing cron jobs ...

What impact does introducing a constraint to a generic type have on the inference process?

Let's take a look at this scenario: function identity<T>(arr: T[]) { return arr } identity(["a", "b"]) In the above code snippet, the generic type T is inferred as string, which seems logical. However, when we introduce a ...

Bootstrap Modal Fails to Display Image Within Its Container

I'm currently working on my e-commerce website, where I'm attempting to implement a feature that allows users to view product images in a modal for a closer look. The product page contains a list of images, and when a user clicks on one, it shoul ...

Getting Angular 2 and Ionic 2 to play nice together: is it worth the effort?

Recently, I attempted to create a glossary app using Ionic 2 and encountered numerous challenges when incorporating the http service. The Angular 2 tutorials had been updated, configuring the mock server proved difficult, and the Ionic 2 documentation offe ...

When null is assigned to a type in Typescript, it does not result in an error being triggered

Could someone enlighten me on why this code is not causing an error? import { Injectable } from '@angular/core'; interface Animal{ name: string; } @Injectable() export class AnimalService { lion: Animal = null; constructor() {} get(){ ...

Dynamic rows in an Angular 2 Material data table

I'm currently working on dynamically adding rows to an Angular 2 Data Table ( https://material.angular.io/components/table/overview) by utilizing a service called "ListService". This service provides me with the columns ("meta.attributes") to be displ ...

Adding a fresh element to an array in Angular 4 using an observable

I am currently working on a page that showcases a list of locations, with the ability to click on each location and display the corresponding assets. Here is how I have structured the template: <li *ngFor="let location of locations" (click)="se ...

Storing multiple email addresses in an array using an HTML input element

I have a small React Bootstrap form where I am trying to save multiple email addresses entered by the user into an array. However, when I use onChange={()=> setEmails(e.target.value as any} it stores them in string format like this --> [email p ...