How to use httpResource to fetch an image and render in HTML as a URL

Discussão em 'Angular' iniciado por Naren Murali, Abril 22, 2025.

  1. Naren Murali

    Naren Murali Guest

    I am experimenting with httpResource, I am trying to fetch an image using the new httpResource method, but I am not sure how to convert the fetched image render in an img tag.

    Below is a sample of what I am trying to do, I checked the network tab and I can see the image is being fetched, but it is not showing inside the image tag.

    Angular.dev - HttpResource Docs

    I think I need to convert this to a URL.

    @Component({
    selector: 'app-root',
    imports: [FormsModule, CommonModule],
    template: `
    <input [(ngModel)]="height" type="number"/>
    <input [(ngModel)]="width" type="number"/>
    <hr/>
    @let imageStatus = imageResource.status();
    @if(imageResource.value(); as imageVal) {
    <img [src]="imageVal"/>
    }
    `,
    })
    export class App {
    sanitizer = inject(DomSanitizer);
    height = signal<number>(200);
    width = signal<number>(300);
    rs = ResourceStatus;
    imageResource = httpResource(
    () => `https://picsum.photos/${this.height()}/${this.width()}`
    );
    }

    Stackblitz Demo

    Continue reading...

Compartilhe esta Página