代码之家  ›  专栏  ›  技术社区  ›  kasia

单击按钮并通过“分量-角度”增加数字

  •  3
  • kasia  · 技术社区  · 9 年前

    嘿, 我的按钮有问题,它应该增加数字+=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;
      }
    }
    

    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>
    

    2 回复  |  直到 9 年前
        1
  •  3
  •   Bojan Gacanovic    8 年前

    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;
        }
    
    }
    
        2
  •  1
  •   FierceDev    9 年前

    试试看:

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

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

    export class CounterService {
      public count = 0;
    }
    

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

    推荐文章