Mike Hawkins
Mike Hawkins

Reputation: 2304

Angular component property doesn't update upon change in referencing property

I have the following component:

<div class="container-fluid">
  {{ testCount }}<button (click)="onClick()">Click</button>
</div>

With the following script:

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  test = []
  testCount = this.test.length

  constructor() {

  }

  onClick() {
    this.test.push({})
    console.log(this.testCount)
  }
}

My issue is, that testCount doens't update in the HTML when i push a new element to the array it references. I'm sure there's a logical explanation behind this, and a possible solution concerning observables, but I can't find out the solution. What am I doing wrong?

Upvotes: 0

Views: 1068

Answers (2)

Barremian
Barremian

Reputation: 31125

The testCount variable won't be updated when you push new elements to the array everytime. It is being assigned the value this.test.length once at the beginning of the component lifecycle and that's it.

Controller

 @Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.scss']
})
export class AppComponent {
  public test = [];
  testCount = this.test.length; // <-- assigned a value once at the beginning and never updated again

  constructor() { }

  onClick() {
    this.test.push({});
    console.log(this.testCount);  // <-- will log 0
  }
}

One quick way would be to use the length property directly in the template

Template

<div class="container-fluid">
  {{ test.length }}<button (mouseup)="onClick()">Click</button>
</div>

Upvotes: 1

Zachary Haber
Zachary Haber

Reputation: 11027

You'd have to update this.testCount when you change the size of test. If you want it to automatically update in the html, just use instead of trying to store the derived property in the component's state. Since it's easy enough to have a single source of truth for the this (test.length).

<div class="container-fluid">
  {{ test.length }}<button (click)="onClick()">Click</button>
</div>

Upvotes: 2

Related Questions