角度隐藏/显示

时间:2017-05-26 19:08:30

标签: html angular angular2-template

我想在积分为100时显示coucou。控制台日志效果很好,但html中的coucou不起作用。

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  points = 100;
  public show = false;
  constructor() {

  }

  coucou() {
    if (this.points == 100) {
      this.show = true;
      console.log("prout");
    }
    else {
      this.show = false;
      console.log("ozdjfezifj");
    }

  }
}

Html方面:

<div *ngIf="coucou()">
  <div style="color:red;">coucou</div>
</div>

4 个答案:

答案 0 :(得分:1)

如果您在*ngIf中使用某个功能,则应返回true或false。在this.show中使用*ngIf

<div *ngIf="show">
  <div style="color:red;">coucou</div>
</div>

或者如果你想使用函数代替this.show,那么从函数中返回true / false

coucou() {
   return this.points == 100 ? true : false; 
 }

或者您可以直接使用

<div *ngIf="points == 100">
  <div style="color:red;">coucou</div>
</div>

答案 1 :(得分:1)

@Transactional(rollbackOn = BusinessException.class) public void save() throws BusinessException { lista.add("Mary"); validar(); lista.add("John"); } private void validar() throws BusinessException{ throw new BusinessException("exception"); } 表达式应该评估为truthy / falsy值。因此,如果函数绑定到ngIf,则应返回ngIftrue

false功能

需要更改
cocou

答案 2 :(得分:0)

因为在ngIf属性值中评估的表达式必须 truthy 而且coucou()似乎没有这样做,因为console.log调用返回undefined

答案 3 :(得分:0)

你可以做并避免所有其他样板

 <div *ngIf="points == 100">
    <div style="color:red;">coucou</div>
 </div>