#angular #typescript #event-handling #mean-stack
#angular #typescript #обработка событий #имеется в виду-стек
Вопрос:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-calculator',
templateUrl: './calculator.component.html',
styleUrls: ['./calculator.component.css']
})
export class CalculatorComponent implements OnInit {
public result:number=0;
public num:number=0;
public final:number=0;
constructor() { }
ngOnInit() {
}
onClick(e){
this.num = Number(e.target.value);
this.result = this.num this.result;
if(e.target.value == "="){
console.log(this.result); // the output of console here is : null
this.display();
}
}
display(){
console.log(this.result); // here the console output is : NaN
this.final = this.result;
}
}
HTML
<div>
<input type="number" value="{{result}}"><br><br>
<button value="1" (click)="onClick($event)">1</button>amp;nbsp;amp;nbsp;
<button value="2" (click)="onClick($event)">2</button>amp;nbsp;amp;nbsp;
<button value="=" (click)="onClick($event)">=</button><br><br>
Result : {{final}}
</div>
Я хочу напечатать результат в функции отображения, но она этого не делает.
даже в функции onClick() результат в операторе if недоступен для области видимости.
Я хочу распечатать результат в функции отображения
Комментарии:
1. Пожалуйста, оформите свой код должным образом, фигурные скобки отсутствуют.
2. Перед добавлением проверьте, является ли
e.target.value
знаком равенства. Прямо сейчас вы делаете это после добавления, которое может иногда заканчиваться вNaN
.3. я проверил это, и когда я выполняю обычную консоль в операторе if, она работает должным образом
4. Когда вы нажимаете кнопку № 3 (где значение равно «=»), вы получите NaN из-за этого
this.num = Number(e.target.value);
=>this.num = Number("=");
=> NaN
Ответ №1:
this.num = Number(e.target.value);//Suppose e.target.value is '='
Вы не можете преобразовать =
символ в число, иначе вы получите NaN
Ваш код должен быть следующим
onClick(e){
if(e.target.value == "="){
console.log(this.result);
this.display();
}
else{
this.num = Number(e.target.value);
this.result = this.num this.result;
}
}
Ответ №2:
Попробуйте изменить порядок в вашем методе onClick, чтобы избежать NaN-исключений. При попытке преобразовать «=» в число вы получите NaN.
onClick(e){
if(e.target.value == "="){
console.log(this.result); // the output of console here is : null
this.display();
} else {
this.num = Number(e.target.value);
this.result = this.num this.result;
}
}
Вот Stackblitz
Ответ №3:
Вы должны проверить if(!isNaN(e.target.value))
в функции onClick.
import { Component } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class AppComponent {
public result:number=0;
public num:number=0;
public final:number=0;
constructor() { }
ngOnInit() {
}
onClick(e){
if(!isNaN(e.target.value)){
this.num = Number(e.target.value);
this.result = this.num this.result;
}
if(e.target.value == "="){
console.log(this.result); // the output of console here is : null
this.display();
}
}
display(){
console.log(this.result); // here the console output is : NaN
this.final = this.result;
}
}
Ответ №4:
Ваше условие if должно быть таким :
onClick(e){
if(e.target.value !=='='){
this.num = Number(e.target.value);
this.result = this.num this.result;
}else{
console.log(this.result);
this.display();
} }
Вы можете проверить это по адресу: Stackblitz.com