Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

click the button and increase number through component - angular

Hej, I'm having having a problem with button which should increase number +=1 and display in the view this number.

app.component.ts

import { Component } from '@angular/core';
import { CounterService } from '../common/services/counter.service';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.sass']
})
export class AppComponent {
constructor(private counterService: CounterService) {}
get count() {
    return this.counterService
  }
  set count(count){
    this.counterService.count += 1;
  }
}

counter.service

export class CounterService {
count = 0;
}

app.component.html

<div class="container">
  <div>
    <p> {{ counterService.count }}</p>
    <button  (click)="count()" class="btn btn-default form-control increaseBtn">INCREASE</button>
  </div>
</div>

I can display 0 but when I'm stacked with incrementation. Thx in advance!

like image 469
kasia Avatar asked Jul 18 '26 16:07

kasia


2 Answers

app.component.ts

<button type="text" class="btn btn-primary" (click)="onShowLog()">Click Me</button>

<p *ngIf="showLog">{{ log }}</p>

app.component.ts

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.sass']
})

export class AppComponent {
    log = 0;
    showLog = false;

    onShowLog(){
         this.showLog = true;
         return this.log = this.log + 1;
    }

}
like image 189
Bojan Gacanovic Avatar answered Jul 20 '26 10:07

Bojan Gacanovic


Try it:

public getCount() {
  return this.counterService.count
}
public incCount(){
  this.counterService.count += 1;
}

in html:

<button  (click)="incCount()" class="btn btn-default form-control increaseBtn">INCREASE</button>

and in counter.service:

export class CounterService {
  public count = 0;
}

But better manage variables in service

like image 22
FierceDev Avatar answered Jul 20 '26 08:07

FierceDev



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!