【问题标题】:Angular "select" input, change variable on option selected角度“选择”输入,在选择的选项上更改变量
【发布时间】:2018-05-20 08:58:24
【问题描述】:

我有问题。 我正在使用 Angular 2。我在 html 中有一个下拉选择,在 TS 文件中有一个变量“selectedVariable”。我想在选择选项时更改 TS 文件中的变量。

例如: 当有人选择:“SCRYPT”时,变量“selectedAlgorithm”将更新为值“SCRYPT”。

我是一个角度初学者,谢谢你的帮助。

HTML:

<select class="form-control" id="allocation-algorithm">
      <option value="SHA-256">SHA-256</option>
      <option value="SCRYPT">SCRYPT</option>
      <option value="ETHASH">ETHASH</option>
      <option value="CRYPTONIGH">CRYPTONIGHT</option>
      <option value="X11">X11</option>
    </select>

TS:

import {Component} from '@angular/core';

import {HashrateAllocationService} from './hashrateAllocation.service';

@Component({
  selector: 'hashrate-allocation',
  templateUrl: './hashrateAllocation.html',
  styleUrls: ['./hashrateAllocation.scss']
})
export class HashrateAllocation {
  selectedAlgorithm = "SHA-256";

  allocationTableData:Array<any>;

  constructor(private _hashrateTableService: HashrateAllocationService) {
    this.allocationTableData = _hashrateTableService.allocationTableData;
  };
}

【问题讨论】:

    标签: angular variables select input


    【解决方案1】:

    使用 Two-way binding [(ngModel)]="selectedAlgorithm"
    Angular 中的双向绑定是模型和视图之间的同步。当模型中的数据发生变化时,视图会反映变化,当视图中的数据发生变化时,模型也会随之更新

    HTML

    <select class="form-control" id="allocation-algorithm" [(ngModel)]="selectedAlgorithm">
          <option value="SHA-256">SHA-256</option>
          <option value="SCRYPT">SCRYPT</option>
          <option value="ETHASH">ETHASH</option>
          <option value="CRYPTONIGH">CRYPTONIGHT</option>
          <option value="X11">X11</option>
        </select>
    

    组件

    import {Component} from '@angular/core';
    
    import {HashrateAllocationService} from './hashrateAllocation.service';
    
    @Component({
      selector: 'hashrate-allocation',
      templateUrl: './hashrateAllocation.html',
      styleUrls: ['./hashrateAllocation.scss']
    })
    export class HashrateAllocation {
      public selectedAlgorithm = "SHA-256";
    
      allocationTableData:Array<any>;
    
      constructor(private _hashrateTableService: HashrateAllocationService) {
        this.allocationTableData = _hashrateTableService.allocationTableData;
      };
    }
    

    DEMO

    【讨论】:

    • 很高兴能帮上忙:)
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-07-06
    • 2013-04-22
    • 2021-11-30
    • 1970-01-01
    • 2021-03-14
    相关资源
    最近更新 更多