Is it possible for variables in a component.ts file to be automatically updated without the need for an updateData()/ngOnit method to be called again within the same component.ts file

I recently started working with Angular and came across a logic issue while implementing a function using a service class in my component class. Here is the code snippet that I encountered:

Link to Stackblitz

app.module.ts

@NgModule({
  declarations: [
    AppComponent,
    AddUserComponent
  ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts

import { UserService } from './services/user.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [UserService]
})
export class AppComponent implements OnInit {
  title = 'UserAvailabe';

  constructor(private userService: UserService) {
  }

  pusers: { name: string; status: string; }[] = [];

  ngOnInit() {
    this.pusers = this.userService.users;
    console.log("ngOnInit called");
  }    
}

app.component.html

<div class="container">
  <app-add-user></app-add-user>
  <div class="user-div" *ngFor="let user of pusers">
    <div class="user-name">{{user.name}}</div>
    <div class="user-status">{{user.status}}</div>
  </div>
</div>

add-user.component.ts

import { UserService } from './../services/user.service';
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-add-user',
  templateUrl: './add-user.component.html',
  styleUrls: ['./add-user.component.css']
})
export class AddUserComponent implements OnInit {

  username: string = '';
  status: string = 'active';

  constructor(private userService: UserService) { }

  ngOnInit(): void {
  }

  addUser() {
    this.userService.addNewUser(this.username, this.status);
    console.log("addUser() called");
    console.log(this.userService.users);
  }

}

add-user.component.html

<div class="form">
    <div class="uName">
        <input type="text" placeholder="Username" id="username" [(ngModel)]="username">
    </div>
    <div class="uStatus">
        <select name="status" id="status" [(ngModel)]="status">
            <option value="active">active</option>
            <option value="inactive">inactive</option>
        </select>
    </div>
    <div class="cUser">
        <button (click)="addUser()">Create User</button>
    </div>
</div>

user.service.ts

export class UserService {

  constructor() { }

  users = [
    { name: 'John', status: 'active' },
    { name: 'Mark', status: 'inactive' },
    { name: 'Steve', status: 'active' }
  ]

  addNewUser(pname: string, pstatus: string) {
    this.users.push({ name: pname, status: pstatus });
  }
}

As per my understanding, initially, the pusers array in app.component.ts gets populated from the service class using ngOnint(). However, when I add a new user by calling the addUser() method in app.service.ts, it updates the users array. Surprisingly, the pusers array in app.component.ts also gets automatically updated without calling ngOnInit() or any other updateData() methods. How does this happen?

Note: Please excuse me if my question seems incorrect. Thank you for your assistance :)

Answer №1

When working with JavaScript, it's important to understand that arrays and objects are passed by reference, not by value. This means that when you assign one variable to another, you're actually just referencing the memory location of the original object or array. To dive deeper into this concept, check out:

https://medium.com/nodesimplified/javascript-pass-by-value-and-pass-by-reference-in-javascript-fcf10305aa9c#:~:text=In%20Javascript%20objects%20and%20arrays%20follows%20pass%20by%20reference.&text=so%20if%20we%20are%20passing,of%20the%20object%20can%20change.

If you need to make a copy of an array without referencing the original, you can do so in the ngOnInit function like this:

this.pusers = [...this.userService.users];

By using this method, you'll be able to avoid any issues related to referencing the original array.

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 KeyValueDiffers within DoCheck limited to working with just a single object per component?

Initially, my ngDoCheck method worked perfectly with just this line: var productChanges = this.differ.diff(this.myProduct); Then I decided to add another object from my component and included the following line: var companyChanges = this.differ.diff(thi ...

Propagating numerical values through iterative iterations

I am currently facing an issue with passing values as props to a component using the forEach method in JavaScript. In addition to passing the existing values from an array, I also want to send another value that needs to be incremented by 1 for each iterat ...

Issue with ADFS 2016 oAuth: Users not being redirected to login page post logout

Having an issue with ADFS 2016 and my Angular application using ng2-adal js for authentication and authorization. After users logout, they are not redirected back to the login page. Debug traces in Event Viewer show the following error: Error: OAuthSignou ...

Encountering notifications and issues pertaining to conflicting dependencies after integrating the angular-oauth2-oidc dependency into the package.json file

I am currently working on an Angular project and wanted to share my package.json file for reference: { "name": "angular.io-example", "version": "0.0.0", "description": "Example project from ...

"Attempting to verify a JSON Web Token using a promise that returns an object not compatible with the specified

Learning about Typescript has been quite a challenge for me, especially when it comes to using the correct syntax. I have implemented a promise to retrieve decoded content from jwt.verify - jsonwebtoken. It is functioning as intended and providing an obje ...

How can I load a separate component.html file using a component.ts file?

Hey there, I'm a beginner with Angular and I have a question about loading a different home.component.html file from a method within books.component.ts. Here's the code snippet from my books.component.ts file: import { Component, OnInit } from ...

Guide to presenting fields on a distinct line or section in Angular 7 forms

I would like to arrange the username area and password area on separate lines with spaces in between. Here is the HTML code snippet: This HTML code is for a login angular GUI. <mat-card class="card"> <mat-card-content> <!-- CONT ...

Angular 8 - Unraveling the Mystery Behind its Initial Page Discovery

I am facing an issue with my Angular 8 application where the login page is being displayed at startup. I have checked the routing module but couldn't find anything that explicitly sets this page as the startup page. Any suggestions on what might be c ...

Angular 2: Sending an HTTP GET request with custom headers and parameters

I have been encountering difficulties while attempting to retrieve data from a Stardog triple store into Angular. Despite successfully accessing the service using curl with matching headers and parameters, I am unable to replicate this functionality with ...

Add a tooltip to the mat-tab title

I have been attempting to implement tooltips on tabs using matTooltip, but I can't seem to get it working. Despite referencing the documentation and searching through Stack Overflow questions, I am unable to identify the root cause of this issue. Cou ...

Support for BigInt is not available in TypeScript version 3.5.*

It seems that TypeScript has supported BigInt since version 3.2, and my project is using TypeScript 3.5. Despite not explicitly declaring any variables as BigInt, I recently integrated a package called BufferUtility from https://github.com/Pharuxtan/Buffer ...

Guide to sending a text from HTML to an Angular 8 Component through the use of the (click) function

After successfully implementing this code: <a [routerLink]="['/menuItemOne']"> <span [innerHTML]="(mystrings$ | async)?.menuItemOne | htmlToText"></span> </a> I now face the challenge of updating t ...

Issue with displaying data using a custom pure pipe and boolean in ngIf condition

For my current web project, I require a friendship/follow feature. There are two roles involved: admins and regular users. Regular users have the ability to follow other users, while admins do not possess this capability. When a user wishes to follow anot ...

The server response value is not appearing in Angular 5

It appears that my client is unable to capture the response data from the server and display it. Below is the code for my component: export class MyComponent implements OnInit { data: string; constructor(private myService: MyService) {} ngOnInit ...

Is the 'case' in a switch statement not treated as a typeguard by Typescript?

Here is a simplified version of the code I am working with: type Todo = { id: string; text: string; }; type Action = | { type: 'DELETE'; payload: string } | { type: 'CREATE'; payload: Todo } function reducer(state: Todo[], ...

Is there a way to specify a custom error type for returned data in rtk query?

Encountered a type error while using rtk query with the following content : Property 'data' does not exist on type 'FetchBaseQueryError | SerializedError'. Property 'data' does not exist on type 'SerializedError' ...

When invoking a service repeatedly in Angular within a loop, the result is returned on the second iteration rather than the first

I've run into an issue where I'm attempting to invoke a service in Angular within a for loop and store the result in a Map. map = new Map<string, string[]>(); this.effectivitiesList = this.trimEffectivities.split(","); for (let ...

Ways to simulate objects in jest

I'm facing an issue while trying to mock a function of an object using Jest and Typescript. Below is a concise version of my code: // myModule.ts export const Foo = { doSomething: () => { // ... does something console.log('original ...

Controlling the visibility of components or elements in Angular through input modifications

Is there a more efficient way to handle button disabling and enabling based on email validation in Angular? I already have form controls set up, but want to make the process cleaner. The goal is to disable the "Get Started" button by default if the email a ...

Ensure that the value of a variable in the Ionic/Angular template has been properly initialized

I am currently facing an issue: I have an array of blog posts. Some of them have photos, while others do not. I aim to display the first photo if any are set. How can I verify whether the URL value in my array is set? <ion-header> <ion-navbar& ...