如何通过单选按钮值初始化变量使用角度6?

时间:2018-06-13 13:05:14

标签: angular

我已经编写了一个简单的代码来练习Angular中的数据绑定,但是我提交单选按钮值时遇到了问题。实际上,我没有任何错误,但是当我调试代码时,我看到typeOfAction变量未定义。

import {Component,OnInit} from '@angular/core';
import {first} from "rxjs/internal/operators";

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

export class CalculatorComponent implements OnInit {
  firstNumber: number=0;
  secondNumber: number=0;
  typeOfAction = '';
  result:string = "";
  constructor() { }

  ngOnInit() {
  }
  onCalc(){
    if(this.typeOfAction == '*'){

      return  this.result =(this.firstNumber * this.secondNumber).toString();
    }else if(this.typeOfAction == '+')
    {
      return this.result = (this.firstNumber - this.secondNumber).toString();
    }else if(this.typeOfAction == '/')
    {
      return this.result = (this.firstNumber / this.secondNumber).toString();
    }else if (this.typeOfAction == '-')
    {
      return this.result =  (this.firstNumber + this.secondNumber).toString();
    }
  }

}
<form>
  <div class="form-group">
  <label for="firstNumber"  >Enter The First Number</label>
    <input type="text" [(ngModel)]="firstNumber" name="firstNumber" class="form-control" id="firstNumber" placeholder="Enter Number">
  </div>
  <div class="form-group">
    <label for="secondNumber">Enter The Second Number</label>
    <input type="text" [(ngModel)]="secondNumber" name="secondNumber" class="form-control" id="secondNumber" placeholder="Enter Number">
  </div><br>
    <div class="form-group">
  <div class="btn-group btn-group-toggle btn-group-lg" data-toggle="buttons">
    <label class="btn btn-secondary active">
      <input type="radio"  [(ngModel)]="typeOfAction" name="typeOfAction" value="*"  id="option1" autocomplete="off" checked>*
    </label>
    <label class="btn btn-secondary">
      <input type="radio" [(ngModel)]="typeOfAction" name="typeOfAction" value="+" id="option2" autocomplete="off">+
    </label>
    <label class="btn btn-secondary">
      <input type="radio" [(ngModel)]="typeOfAction" value="-" name="typeOfAction" id="option3" autocomplete="off"> -
    </label>
    <label class="btn btn-secondary">
      <input type="radio" [(ngModel)]="typeOfAction" value="/" name="typeOfAction" id="option4" autocomplete="off"> /
    </label>
  </div>
    </div>
  <br>
  <br>
  <button class="btn btn-block btn-primary" (click)="onCalc()">Calculate</button>
</form>
<br>
<br>

<label class="alert alert-success" role="alert">
  {{result}}
</label>

1 个答案:

答案 0 :(得分:0)

使用MatRadioModule将ngModel属性绑定到无线电输入类型:

在.ts文件中,使用您要选择的值初始化该属性:

typeOfAction = '*';

用HTML代替无线电输入:

<mat-radio-group [(ngModel)]="typeOfAction" name="typeOfAction">
    <mat-radio-button value="*"> * </mat-radio-button>
    <mat-radio-button value="+"> + </mat-radio-button>
    <mat-radio-button value="-"> - </mat-radio-button>
    <mat-radio-button value="/"> / </mat-radio-button>
</mat-radio-group>