2017-07-25 67 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; 
    } 

}