简体   繁体   中英

Angular “select” input, change variable on option selected

I have a problem. I'm using Angular 2. I have a dropdown selection in the html and a variable "selectedVariable" in the TS file. I want to change the variable in the TS file when a option is selected.

For example: When someone selects: "SCRYPT", the variable "selectedAlgorithm" gets updated with the Value "SCRYPT".

I'm a angular beginner, thank you for the help.

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;
  };
}

Use Two-way binding [(ngModel)]="selectedAlgorithm"
Two-way Binding in Angular is the synchronization between the model and the view. When data in the model changes, the view reflects the change, and when data in the view changes, the model is updated as well

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>

Component

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM