【问题标题】:My buttons wont enter into my input field Angular我的按钮不会进入我的输入字段 Angular
【发布时间】:2021-02-11 09:46:45
【问题描述】:

我正在尝试从 youtube 视频中制作一个简单的计算器。每次我按下其中一个生成的按钮时,代码都不会执行任何操作。我的控制台也没有错误。它根本不起作用

此代码在我的calculator.components.ts 中:


@Component({
  selector: 'app-calculator',
  templateUrl: './calculator.component.html',
  styleUrls: ['./calculator.component.css']
})
export class CalculatorComponent implements OnInit {

buttons = [1, 2, 3, 4, 5, 6, 7, 8, 9, 0, '.', '+', '-', '*', '/', '=','CLEAR'];
val = ''
  constructor() { }

calc($event) {
  console.log("hi");

  var button = $event.srcElement.innerText;
  if (button === '='){
    this.val = eval(this.val);
  }else if ( button === 'CLEAR'){
    this.val = ''
  }else {
    console.log();
    this.val += button;
  }
}

  ngOnInit(): void {
  }

}

以下代码在我的calculator.component.html中:

<input [(ngModel)]="val" type="text">
<div>
<button *ngFor="let button of buttons">{{button}}</button>
</div>

html页面的截图

【问题讨论】:

    标签: html angularjs typescript


    【解决方案1】:

    您忘记在按钮中输入 (click) 以运行您的 calc() 函数

    模板

    <button *ngFor="let button of buttons"
            (click)="$event">{{button}}</button>
    

    或者你也可以这样实现:

    模板

    <button *ngFor="let button of buttons"
            (click)="button">{{button}}</button>      // Passing your button name on click event
    

    组件

    calc(buttonName) {
      console.log("hi");
    
      if (buttonName === '='){
        this.val = eval(this.val);
      } else if (buttonName === 'CLEAR'){
        this.val = ''
      } else {
        console.log();
        this.val += button;
      }
    }
    
    ________________________________________________________
    
    // You can enhance the above code to:
    calc(buttonName) {
      console.log("hi");
    
      this.val = buttonName === '='
        ? eval(this.val)
        : buttonName === 'CLEAR'
        ? ''
        : this.val += button;
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-03
      • 2015-01-29
      • 1970-01-01
      • 2021-02-16
      相关资源
      最近更新 更多