user6600549
user6600549

Reputation:

How to increment variable in angular 2 - 4

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%');

  }



}

Upvotes: 0

Views: 4489

Answers (1)

Jayakrishnan
Jayakrishnan

Reputation: 4294

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!!

Upvotes: 3

Related Questions