Hojat Afsharan
Hojat Afsharan

Reputation: 60

Using Pipe on two related variables in Angular ngModel

I have two inputs that take temps like this: one in Fahrenheit and another in Celcius. If the user enters a number in C, the input of F should be filled with the proper conversion in Fahrenheit and vice versa. But the problem is when I want to use a pipe to show the result with 1 decimal number. There are many solutions with one input. But I could not find any way to implement it with two inputs.

HTML file:

  <section>
    <label>Celsius: </label>
    <input type="number" [ngModel]="tempC | number:'1.0-1" (ngModelChange)="modelChangedC()"/>
  </section>

  <section >
      <label>Fahrenheit: </label>
      <input type="number"  [ngModel]="tempF | number:'1.0-1" (ngModelChange)="modelChangedF()"/>
  </section>

typescript file:

  tempF: number = 0;
  tempC: number = 0;
   
  modelChangedC() {
    this.tempF = this.tempC*9/5 + 32;
  }

  modelChangedF() {
    this.tempC = (this.tempF - 32) * 5/9;
  }

Upvotes: 1

Views: 358

Answers (1)

rhavelka
rhavelka

Reputation: 2396

for ngModel to two way bind it you need to use the syntax [(ngModel)] but you can't do that because you are using a pipe. To get around this you need to capture the $event that comes from the ngModelChange emission. This can be done as follows

HTML:

  <section>
    <label>Celsius: </label>
    <input type="number" [ngModel]="tempC | number:'1.0-1'" (ngModelChange)="modelChangedC($event)"/>
  </section>

  <section >
      <label>Fahrenheit: </label>
      <input type="number"  [ngModel]="tempF | number:'1.0-1'" (ngModelChange)="modelChangedF($event)"/>
  </section>

TS:

  tempC = 0;
  tempF = 0;

  modelChangedC(ev) {
    this.tempC = ev;
    this.tempF = this.tempC*9/5 + 32;
  }

  modelChangedF(ev) {
    this.tempF = ev;
    this.tempC = (this.tempF - 32) * 5/9;
  }

here is working stackblitz

Also note that you are missing the closing single quote in your pipe declaration. It should be "tempC | number:'1.0-1'" not "tempC | number:'1.0-1"

Upvotes: 1

Related Questions