After switching from Angular JS 1.6 to Angular 6, I encountered a problem while working on an app in Angular 6. The [(ngModel)]="number1"
directive for 2-way data binding caused my component to stop rendering. When I switched to (ngModel)
, the component rendered but the model variable did not bind any data.
Adding public number1: number = 22;
to my component's TypeScript code did not result in the value being data binded.
I'm using TypeScript version 2.9 and it accepts let we = "Hello"
, but throws an error for "Unexpected Token."
I'm wondering if Angular in Angular 6 creates variables in a similar way to Angular JS, where simply writing a variable in HTML bound with ng-Model automatically adds the variable to the $scope object. Does the same mechanism apply in Angular 6?
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-calculator',
templateUrl: './calculator.component.html',
styleUrls: ['./calculator.component.scss']
})
export class CalculatorComponent {
//var foo = 'Hello TypeScript!';
public number1: number = 22;
public number2: number = 22;
public result: number;
public add() {
alert(this.number1);
alert(this.number2);
this.result = this.number1 + this.number2;
}
}
<div class="container">
<div class="header">
<h2>
Calculator component
</h2>
</div>
<div class="grid">
<div class="row">
<div class="col-6">
<div class="operation">
<div class="row">
<div class="col-12">
<input type="number" placeholder="number" [(ngModel)]="number1">
</div>
</div>
<div class="row">
<div class="col-12">
<input type="number" placeholder="number" [(ngModel)]="number2">
</div>
</div>
<div>
<div class="col-12">
<button class="button" (click)="add()">
Add
</button>
</div>
</div>
</div>
</div>
<div class="col-6">
<div class="result">
<span>
Result : {{result}}
</span>
</div>
</div>
</div>
</div>
</div>