Home > database >  Angular variable value change doesn't reflect in DOM
Angular variable value change doesn't reflect in DOM

Time:10-28

I have an Angular component (SummaryComponent) which is injected with a service (LicenseRequestService). A variable (totalLicense) of the component is defined to be equal to a calculated field from the service.

The component class is written as below :

import { Component, OnInit } from '@angular/core';
import { LicenseRequestService } from '../shared/license-request.service';

@Component({
  selector: 'sg-summary',
  templateUrl: './summary.component.html',
  styleUrls: ['./summary.component.css']
})
export class SummaryComponent implements OnInit {

  constructor(private _service : LicenseRequestService) {

   }

   public totalLicense= this._service.licenseDetails.length


  ngOnInit(): void {
    
  }

  updateSummary(){
    const licenses= this._service.licenseDetails.length
    console.log("total players requested : "   players)
    this.totalLicense= players
  }

}

I have embeded the totalLicense value into the DOM as below :

<div>
    Total number of licenses is : {{totaLicense}}
</div>

<button type="submit" (click)="updateSummary()">Get licenses</button>

Everytime the service gets updated, I expect the DOM to reflect the updated value of totalLicense but it stays 0. However, when I click the button labeled Get licenses, the DOM is then updated and the totaLicense variable shows the new value in the browser.

Do I need to make any changes to make sure the value of totalLicense gets updated without clicking the button (which is the desired functionality)?

CodePudding user response:

Try to put this public totalLicense= this._service.licenseDetails.length code constructor or ngOnInit

CodePudding user response:

Your problem is you're not passing a reference you are passing a value. Basically if you have the following:

let x = 'test';
let y = x;
x = 'update';
console.log(y);
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe> This code will output 'test', not 'update' because y is still pointing at the original value

There are three solutions I can think of offhand:

  1. Reference the service itself in the html (you'd have to make it not private)
  2. Add licenseDetails as a variable in your component instead. This way when you access the length variable it will be by reference, not by value
  3. Use a getter (not suggested since it is an antipattern, since it causes the function to run on each change detection cycle)
  • Related