Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular "select" input, change variable on option selected

Tags:

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;
  };
}
like image 921
BlockchainProgrammer Avatar asked May 20 '18 08:05

BlockchainProgrammer


1 Answers

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

like image 107
Vikas Avatar answered Sep 28 '22 17:09

Vikas