【问题标题】:click the button and increase number through component - angular单击按钮并通过组件增加数量 - 角度
【发布时间】:2017-12-31 04:38:57
【问题描述】:

嘿嘿, 我遇到了按钮问题,它应该增加数字 +=1 并在视图中显示这个数字。

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>

我可以显示 0,但是当我堆叠增量时。提前谢谢!

【问题讨论】:

标签: angular button service components increment


【解决方案1】:

试试看:

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

在html中:

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

在 counter.service 中:

export class CounterService {
  public count = 0;
}

但更好地管理服务中的变量

【讨论】:

    【解决方案2】:

    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;
        }
    
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-03-13
      • 1970-01-01
      • 2018-01-08
      • 1970-01-01
      • 2014-09-20
      • 1970-01-01
      • 2020-06-13
      • 1970-01-01
      相关资源
      最近更新 更多