Home > Enterprise >  How to subscribe to input for it to save changes into an object?
How to subscribe to input for it to save changes into an object?

Time:02-08

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.

CodePudding user response:

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

CodePudding user response:

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)"

CodePudding user response:

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.

  •  Tags:  
  • Related