Conditions with typescript

Asked

Viewed 913 times

1

I’m trying to make a if in typescript but it simply gets ignored and never enters the condition.

My typescript code:

import { Component } from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';

@Component({
  selector: 'page-jogomemoria',
  templateUrl: 'jogomemoria.html',
})
export class JogomemoriaPage {

  constructor(public navCtrl: NavController, public navParams: NavParams) {}


  vira1() {
    document.getElementById("virada0").style.zIndex = "999";
    verificaViradasCima++;
  }


  if (verificaViradasCima = 2) {
    alert("Voce clicou duas vezes");
  }
}
var verificaViradasCima = 0;

Why does this happen ?

  • Whenever you use the code here on live snippet format it by clicking on the "Organize" button that appears in the left bar. This makes it much easier to read for anyone who wants to reply.

3 answers

1

Lacked a =...

  • Use = for assignment.
  • Use == or === for comparison.
  • I’ve tried but he ignores it the same way.

1


You must define the variables in the method constructor, take this example:

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

@Component({
  selector: 'my-app',
  template: `<h1>Olá {{name}}</h1><button (click)="exeDecrementar()">Decrementar</button>{{verificaViradasCima}}<button (click)="exeIncrementar()">Incrementar</button>`
})
export class AppComponent {
    // Lembrando que isso é apenas um exemplo,
    // logo você deve alterar conforme sua necessidade
    constructor() {
        // Declara as variáveis.
        this.name = "Lone Tonberry";
        this.verificaViradasCima = 0;
    }

    exeDecrementar() {        
        // Se for maior que zero faz decremento.
        if (this.verificaViradasCima > 0) {
            this.verificaViradasCima--;
        }
    }

    exeIncrementar() {
        // Se for igual a 2 mostra o alerta.
        if (this.verificaViradasCima == 2) {
            alert("Voce clicou duas vezes");
        } else {
            // Se não for faz incremento.
            this.verificaViradasCima++;
        }
    }
}

You can see running Plunker

0

In Typescript you can perform an assignment during a comparison and this can cause some confusion (Using a single sign of equals). In the Ecmascript specification, where Javascript and Typescript are based, you should use two equals signals to compare if the values of two variables are equivalent and use three signals to compare if they are equal.

// O resultado é true
(1 == "1");
(1 == true);
("00.00" == 0)
(null == undefined)

// O resultado é falso
(1 === "1")
("0" === 0)
(false === 0)

What == does behind, basically, is first try to transform the two values compared in number, it seems kind of bizarre, but it’s life.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.