angularangular-dom-sanitizerangular-signalsangular-input

Angular Input Signals and sanitized values


I thought that I can use an URL as input Signal in my preview.component like

hrefLink = input.required<SafeValue>();

and in the .html use it like

<img [src]="hrefLink"/>

I have configured in my config.component.ts:

useLink:SafeValue;
...
initMethod() {
  this.useLink=this.domSanitizer.bypassSecurityTrustResourceUrl(
    myNavigationURL
  )

and use it in the config.component.html

<app-preview [hrefLink]="useLink"/>

But matter of fact I get an error saying:

 unsafe:[Input Signal: SafeValue must use [property]=binding

Do I miss something or is there a hole in the TypeCheck?


Solution

  • Please call the signal like below before sending to [src], we need to execute it, before sending it as an input to the src property binding!

    import { Component, input } from '@angular/core';
    import { SafeValue } from '@angular/platform-browser';
    
    @Component({
      selector: 'app-preview',
      standalone: true,
      imports: [],
      template: `<img [src]="hrefLink()"/>`, // <- changed here!
    })
    export class PreviewComponent {
      hrefLink = input.required<SafeValue>();
    }
    

    FULL CODE:

    PREVIEW:

    import { Component, input } from '@angular/core';
    import { SafeValue } from '@angular/platform-browser';
    
    @Component({
      selector: 'app-preview',
      standalone: true,
      imports: [],
      template: `<img [src]="hrefLink()"/>`,
    })
    export class PreviewComponent {
      hrefLink = input.required<SafeValue>();
    }
    

    PARENT:

    import { Component, inject } from '@angular/core';
    import {
      DomSanitizer,
      SafeValue,
      bootstrapApplication,
    } from '@angular/platform-browser';
    import 'zone.js';
    import { PreviewComponent } from './app/preview/preview.component';
    
    @Component({
      selector: 'app-root',
      standalone: true,
      imports: [PreviewComponent],
      template: `
        <app-preview [hrefLink]="useLink"/>
      `,
    })
    export class App {
      myNavigationURL = 'https://placehold.co/600x400';
      useLink!: SafeValue;
      domSanitizer = inject(DomSanitizer);
    
      ngOnInit() {
        this.useLink = this.domSanitizer.bypassSecurityTrustResourceUrl(
          this.myNavigationURL
        );
      }
    }
    
    bootstrapApplication(App);
    

    Stackblitz Demo