Reputation: 31
I have an input in a form of HTML like this:
<mat-form-field appearance="fill">
<mat-label>Flowrate: </mat-label>
<input id = "flowRate" type="number" matInput>
</mat-form-field>
To which I subscribe later in my .ts file like this:
private flowRateInput: any = document.getElementById('flowRate') as HTMLInputElement
if (flowRateInput: any) {
let flowObs = fromEvent(this.flowRateInput, 'input').pipe(
debounceTime(500)
).subscribe(res => {
this.calcData.flowRate = +this.flowRateInput.value;
console.log(this.flowRateInput.value)
console.log(this.calcData)
})
}
However it seems to do nothing when I open the page and change the input. I have a guess that I did something wrong in subscribe part of the code.
Upvotes: 0
Views: 773
Reputation: 2194
Using document.getElementById('flowRate')
is discouraged when you are using Angular, instead, you should template-driven forms or reactive-forms, which is the angular way of doing so.
I'll show the reactive-form example
First import the ReactiveFormsModule
in your app.module.ts
, so that FormControls work in your example.
<mat-form-field appearance="fill">
<mat-label>Flowrate: </mat-label>
<input [formControl]="flowRateControl" type="number" matInput>
</mat-form-field>
In your .ts
component
flowRateControl: FormControl = new FormControl();
ngOnInit(): void {
this.flowRateControl.valueChanges.subscribe(val => {
console.log(val);
});
}
Also, the benefits of using this approach are that you can use multiple RxJs operators like debounce
, distinctUntilChanged
which can boost your user experience.
Upvotes: 1
Reputation: 2361
you don't need to subscript and you don't need to to do document.getElementById('flowRate') in angular.
you can use ngModel for example:
<input type="number" matInput [(ngModel)]="flowRate">
private _flowRate="";
set flowRate(flowRate){
this._flowRate = flowRate;
this.calcData.flowRate = +this.flowRateInput.value;
}
get flowRate(){
return this._flowRate;
}
or you can listen to the change event:
<input type="number" matInput (change)="flowRateChange($event)>
or <input type="number" matInput [ngModel]="flowRate" (ngModelChange)="flowRateChange($event)"
Upvotes: 1
Reputation: 174
Try something like this, using FormControl :
.html file:
<mat-form-field appearance="fill">
<mat-label>Flowrate: </mat-label>
<input id="flowRate" type="number" [formControl]="fcFlowRate" matInput>
</mat-form-field>
.ts file :
// Before constructor
fcFlowRate = new FormControl();
// In NgOnInit
this.fcFlowRate.valueChanges.pipe(debounceTime(500)).subscribe( value => {
this.calcData.flowRate = +value;
console.log(value)
console.log(this.calcData)
})
Upvotes: 1