Skip to content

Instantly share code, notes, and snippets.

@tedhagos
Last active December 17, 2018 02:07
Show Gist options
  • Save tedhagos/4d7d05e636327699ec63c26f8ba6b230 to your computer and use it in GitHub Desktop.
Save tedhagos/4d7d05e636327699ec63c26f8ba6b230 to your computer and use it in GitHub Desktop.
Guessing game exercise in Angular
<h1>{{ title }}</h1>
<strong>Can you guess a number betwee 1 to 100?</strong>
<p>
<input placeholder="type an integer" [(ngModel)]="guess">
</p>
<button (click)="guessTheNumber()">
Guess the number
</button>
<p></p>
<div class="right" *ngIf="isAnswered">
You guessed it right the number is {{ theNumber }}
</div>
<div class="try_again" *ngIf="tryAgain">
Try again
</div>
<div class="try_again" *ngIf="showHint">
{{ hint }}
</div>
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
title = 'guessinggame';
guess:number;
theNumber:number;
isAnswered:boolean = false;
tryAgain:boolean = false;
showHint = false;
hint:string = "";
constructor() {
this.theNumber = Math.floor(Math.random() * 100);
console.log(this.theNumber);
}
guessTheNumber() {
if(this.guess == this.theNumber) {
console.log(`that's right, the number is ${this.theNumber}`);
this.isAnswered = true;
this.showHint = false;
}
else {
console.log("try again");
// this.tryAgain = true;
this.isAnswered = false;
if (this.guess < this.theNumber) {
this.showHint = true;
this.hint = "the number is higher";
}
else {
this.showHint = true;
this.hint = "the number is lower"
}
}
}
}
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule} from '@angular/forms';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment