Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular typescript concatenating numbers instead of adding

I have three users , when I click on next it has to load route for next user, SO I am adding one to id and passing to routerLink, bu somehow instead of adding it is concatenating the numbers, Below is the code

import { Component, OnInit, OnDestroy } from '@angular/core';
import { ActivatedRoute,Params } from '@angular/router';
import { Subscription } from 'rxjs/Subscription';
@Component({
  selector: 'app-user',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.css']
})
export class UserComponent implements OnInit,OnDestroy {
  routeSubscription : Subscription;
  id : number;
  next :  number = 0;
  constructor(private route:ActivatedRoute) { 
  }

  ngOnInit() {
  this.routeSubscription =  this.route.params.subscribe((params :Params) =>{
    this.id = params['id'];
    this.next = this.id  + 1;
  });
  }
  ngOnDestroy(){
    this.routeSubscription.unsubscribe();
  }
}

Html Template for this

<p>
  user id : {{ id }}
</p>

<button class="btn btn-primary" [routerLink] = "['/Users', next ]">Next</button>

Please Let me know why next is getting concatenated with id

like image 746
Yashwanth Potu Avatar asked Apr 25 '26 04:04

Yashwanth Potu


2 Answers

The problem is that the value of the id as returned by the params object in this.id = params['id']; is a string value.

The following should fix your problem

this.next = +this.id  + 1; // The id is cast to a number with the unary + operator
like image 58
JeanPaul A. Avatar answered Apr 26 '26 17:04

JeanPaul A.


Probably the problem is that this.id = params['id'] is setting a string to this.id, and then 'this.id + 1;' is the same as "'1' + 1";

Try to parse it as integer

this.id = parseInt(params['id'], 10); 
like image 33
Christian Benseler Avatar answered Apr 26 '26 19:04

Christian Benseler



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!