To create an Angular pipe that converts RGB color codes to hexadecimal format, follow these steps:
Generate the Pipe:
Use Angular CLI to create a pipe:
ng generate pipe rgbToHex
Implement the Pipe:
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({ name: 'rgbToHex' })
export class RgbToHexPipe implements PipeTransform {
transform(rgb: string): string {
const rgbValues = rgb.match(/\d+/g);
if (!rgbValues || rgbValues.length !== 3) {
return rgb; // Return input if invalid
}
const [r, g, b] = rgbValues.map(num => {
const hex = parseInt(num).toString(16).padStart(2, '0');
return hex;
});
return `#${r}${g}${b}`.toUpperCase();
}
}
Declare the Pipe:
import { NgModule } from '@angular/core';
import { RgbToHexPipe } from './rgb-to-hex.pipe';
@NgModule({
declarations: [RgbToHexPipe],
// ...
})
export class AppModule {}
Use in Template:
Apply the pipe to convert RGB to hex:
<div>{{ 'rgb(255, 128, 0)' | rgbToHex }}</div>
<!-- Output: #FF8000 -->
<div>{{ '255, 128, 0' | rgbToHex }}</div>
<!-- Output: #FF8000 -->