Nesse projeto eu apanhei um pouco, pois não estava conseguindo fazer a reatividade dos 3 inputs. A ideia do projeto era simples, um conversor de **Celsius**, **Fahrenheit** e **Kelvin**.
Publicado em 30 de abril de 2026
Nesse projeto eu apanhei um pouco, pois não estava conseguindo fazer a reatividade dos 3 inputs. A ideia do projeto era simples, um conversor de Celsius, Fahrenheit e Kelvin.
Se o usuário digita o valor no input de Celsius, ele deve fazer a conversão para Fahrenheit e Kelvin, o mesmo deveria acontecer nos demais campos.
Sabendo das fórmulas abaixo, comecei a colocar a mão na massa.
Primeiro já criei aquele formulário de respeito usando o FormGroup e FormBuilder
<form [formGroup]="converter">
<div>
<label for="celsius">Celsius</label>
<input id="celsius" type="number" formControlName="celsius" name="celsius">
</div>
<div>
<label for="fahrenheit">Fahrenheit</label>
<input id="fahrenheit" type="number" formControlName="fahrenheit" name="fahrenheit">
</div>
<div>
<label for="kelvin">Kelvin</label>
<input id="kelvin" type="number" formControlName="kelvin" name="kelvin">
</div>
</form>
export class Converter implements OnInit {
converter: FormGroup;
constructor(private fb: FormBuilder) {
this.converter = this.fb.group({
celsius: [null],
fahrenheit: [null],
kelvin: [null]
})
}
}
Aqui basicamente eu estou iniciando os valores celsius,fahrenheit e kelvin como null. Esses campos são os mesmos do formControlName no html.
Em seguida, usei o Observable valueChanges para disparar um evento assim que detecta uma mudança, no meu caso ao digitar eu quero capturar o valor.
Com isso, dentro do ngOnInit eu criei o evento que será disparado dentro do input 'celsius'
this.converter.get('celsius')?.valueChanges.subscribe(value => {
this.updateFromCelsius(value);
});
Para usar o valueChanges temos que invocar o subscribe e dentro dele passamos uma função, no exemplo acima ele pega o valor do input (value) e coloca como argumento da função: this.updateFromCelsius(value)
Em seguida criamos a função:
private updateFromCelsius(celsius: number): void {
if (celsius === null) return;
this.converter.patchValue({
fahrenheit: (celsius * 9 / 5) + 32,
kelvin: celsius + 273.15
}, { emitEvent: false });
}
Na função updateFromCelsius, nós simplesmente criamos um if para tratar a nulidade, ou seja, se o valor for null nem execute a função. Depois disso, usamos patchValue, pois o patchValue faz com que eu atualizei apenas alguns campos já o setValue() obriga a preencher todos os campos. E por fim, tendo as fórmulas eu basicamente associo com cada input. O mesmo acontece para os demais, ficando o código completo assim:
<form [formGroup]="converter">
<div>
<label for="celsius">Celsius</label>
<input id="celsius" type="number" formControlName="celsius" name="celsius">
</div>
<div>
<label for="fahrenheit">Fahrenheit</label>
<input id="fahrenheit" type="number" formControlName="fahrenheit" name="fahrenheit">
</div>
<div>
<label for="kelvin">Kelvin</label>
<input id="kelvin" type="number" formControlName="kelvin" name="kelvin">
</>
import { Component, OnInit } from '@angular/core';
import { FormBuilder, FormGroup, ReactiveFormsModule } from '@angular/forms';
@Component({
selector: 'app-converter',
imports: [ReactiveFormsModule],
templateUrl: './converter.html',
styleUrl: './converter.scss',
})
export class Converter implements OnInit {
converter: FormGroup;
constructor(private fb: FormBuilder) {
this.converter = this.fb.group({
celsius: [null],
fahrenheit: [null],
kelvin: [null]
})
}
ngOnInit(): void {
this.converter.get('celsius')?.valueChanges.subscribe( => {
.(value);
});
..()?..( {
.(value);
});
..()?..( {
.(value);
});
}
(: ): {
(celsius === ) ;
..({
: (celsius * / ) + ,
: celsius +
}, { : });
}
(: ): {
(fahrenheit === ) ;
celsius = (fahrenheit - ) * / ;
..({
celsius,
: celsius +
}, { : });
}
(: ): {
(kelvin === ) ;
celsius = kelvin - ;
..({
celsius,
: (celsius * / ) +
}, { : });
}
}
É isso ai, espero que tenham curtido, abraços!
Carregando comentários...