BlockchainProgrammer
BlockchainProgrammer

Reputation: 2069

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

Upvotes: 6

Views: 21639

Answers (1)

Vikas
Vikas

Reputation: 12036

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

Upvotes: 6

Related Questions