angulartypescript

Display/Edit a number in hex format


Is there any built in way with Angular to use a Number type in my model as Hex Value in the HTML for Displaying and Editing? I have this type in my model:

bitmask: number = 0;

Which should now be presented as Hex Value in the frontend.

<td *ngIf="!isEditing">{{parameter.bitmask}}</td>
<td *ngIf="isEditing"><input type="text" [(ngModel)]="parameter.bitmask" maxlength="2" pattern="^(0-9a-fA-F)$" /></td>

Any hint or help would be appriciated. I already tried it with a property in the model like this:

get hexBitmask(): string {
    return this.bitmask.toString(16);
}

set hexBitmask(value: string) {
    if (!value.startsWith('0x')) {
        value = "0x".concat(value);
    }       
        
    this.bitmask = Number(value);
}

But it seems like I cannot use this in the binding on my frontend the same way as I did it with the bitmask field.


Solution

  • As an option for showing you can use a custom pipe:

    import { Pipe, PipeTransform } from '@angular/core';
    
    @Pipe({
      name: 'customPipe',
      standalone: true
    })
    export class CustomPipe implements PipeTransform {
    
      transform(value: number): string[] {
        return this.bitmask.toString(16);
      }
    }
    

    in html you will have next:

    <td *ngIf="!isEditing">{{parameter.bitmask | customPipe}}</td>
    

    For inputting the data, you have not described what format is going to be with '0x' or without.