My question is different to
Get mdslider value in angular 2?
in that I needed to pass the value of the slider to the component, not
just use a local variable; but also in respect of Angular Material
having changed so that the slider now requires an $event object to be
passed to the component function.
I have an Angular Material slider component in Angular 4:
HTML
<mat-slider min="430" max="500" step="10" value="450" (input)="pitch($event)"></mat-slider>
TS
import { Component, OnInit } from '@angular/core';
import { Inject, Injectable } from '@angular/core';
import { MatSlider } from '@angular/material';
import { AudioContext } from 'angular-audio-context';
@Component({
selector: 'pitch-slider',
templateUrl: './pitch-slider.component.html',
styleUrls: ['./pitch-slider.component.css']
})
export class PitchSliderComponent implements OnInit {
constructor(private _audioContext: AudioContext) { }
ngOnInit() {
}
}
I am quite new to Angular and I'm having trouble getting the current value of the slider. It doesn't seem to work with $event object?
I was confused about the $event object - I needed to ref it with just event in the component.ts:
HTML
<h2>freq.</h2>
<button class="btn btn-primary" (click)="play()">Play</button>
<mat-slider min="430" max="500" step="10" #matslider (input)="pitch($event)"></mat-slider>
<div>
{{ matslider.value }}
</div>
TS
import { Component, OnInit } from '@angular/core';
import { Inject, Injectable } from '@angular/core';
import { MatSlider } from '@angular/material';
import { AudioContext } from 'angular-audio-context';
@Component({
selector: 'pitch-slider',
templateUrl: './pitch-slider.component.html',
styleUrls: ['./pitch-slider.component.css']
})
export class PitchSliderComponent implements OnInit {
value: 450;
constructor(private _audioContext: AudioContext) { }
ngOnInit() {
}
pitch(event: any) {
console.log(event.value);
}
play() {
console.log("play clicked!");
var frequency = this.value;
var volume = 0.2;
var oscillator = this._audioContext.createOscillator();
var gainNode = this._audioContext.createGain();
oscillator.connect(gainNode);
gainNode.connect(this._audioContext.destination);
gainNode.gain.value = volume;
oscillator.frequency.value = frequency;
oscillator.start();
setTimeout(
function(){
oscillator.stop();
}, 500
);
}
}
With (input) event when you click outside of mat-slider, it still fired this event.
I changed it to (change) event.
This is my way to display value of mat-slider, I share for whom concern.
TS file
export class SliderOverviewExample {
gridsize: number = 30;
updateSetting(event) {
this.gridsize = event.value;
}
}
HTML file
<div>
<span>Grid Size (px): </span><b class="gridSizeValue">{{gridsize.value}}</b>
</div>
<mat-slider #gridsize (change)="updateSetting($event)"
step="5" min="10" max="100" [value]="gridsize"></mat-slider>
Demo https://stackblitz.com/edit/angular-display-mat-slider-value?file=app/slider-overview-example.html