2017-07-25 53 views
0

Hej, 我有一個問題,應該增加數字+ = 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,但是當我堆疊增量。 Thx提前!

+1

您正在使用的二傳手在一個錯誤的方式。請閱讀https://www.typescriptlang.org/docs/handbook/classes.html中的訪問器部分 –

回答

0

試試:

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

但在服務

0

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

}