角度输入信号和净化值

问题描述 投票:0回答:1

我认为我可以在我的

input
中使用 URL 作为
preview.component
信号

hrefLink = input.required<SafeValue>();

并在

.html
中像

一样使用它
<img [src]="hrefLink"/>

我已经在我的

config.component.ts
中配置了:

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

并在

config.component.html

中使用它
<app-preview [hrefLink]="useLink"/>

但事实上我收到一条错误消息:

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

我是否遗漏了什么或者 TypeCheck 中是否有漏洞?

angular angular-dom-sanitizer angular-signals angular-input
1个回答
0
投票

请在发送到

[src]
之前调用如下信号,我们需要在将其作为输入发送到 src 属性绑定之前执行它!

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>();
}

完整代码:

预览:

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>();
}

家长:

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 演示

© www.soinside.com 2019 - 2024. All rights reserved.