0

How to increment a variable in angular 2 - 4

When I go from page 1 to page 2 for some reasons this variable (n) is not incremented.

I want every time the page loads the variable n to increment by 1, after I route 20 times to this page, I want to log 20,

export class DashboardComponent implements OnInit, AfterViewInit {

  public n: number = 0; // I want to increment this.


  constructor(private router: Router) { }

  ngOnInit() { }

  ngAfterViewInit() {

    // google.charts.setOnLoadCallback(() => this.chart_1('500', '100%'));

    console.log('-------- ngAfterViewInit -------');

    let chartwidth1 = $('#curve_chart1').width();
    let chartwidth2 = $('#curve_chart2').width();

    if ( this.n === 0) {
      chartwidth1 += 0;
      chartwidth2 += 0;
    } else {
      chartwidth1 -= 50;
      chartwidth2 -= 50;
    }

    console.log(chartwidth1);
    console.log(chartwidth2);

    console.log(this.n); // 0
    this.n += 1;
    console.log(this.n); // 1

    // google.charts.setOnLoadCallback(() => this.chart_1((chartwidth1 - 80), '100%'));

    this.chart_1((chartwidth1 - 80), '100%');
    this.chart_2((chartwidth2 - 80), '100%');

  }



}
1
  • for the people who come here only to downvote, this question don't come here just help if you can, or explain why you downvote this simple question malakopitoures Commented May 27, 2017 at 15:27

1 Answer 1

3

You need to have that variable in an injectable service and make that service shared.

Service

@Injectable()
 export class SharedService {
   public n:number;
 }

app module

@NgModule({
 imports: [BrowserModule,
          HttpModule],
  declarations: [AppComponent],
  providers: [SharedService],
  bootstrap: [AppComponent]
 }) export class AppModule { }

your component

import {SharedService} from 'path of service folder';
export class DashboardComponent implements OnInit, AfterViewInit {

constructor(private router: Router,private sharedService:SharedService) {
 }

 ngAfterViewInit() {
   this.sharedService.n +=1;
  }
}

Hope it helps!!

Sign up to request clarification or add additional context in comments.

1 Comment

you are welcome. I would be happy if it resolves your problem. Don't forget to accept it as answer if it solves your issue. Have a nice day :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.