錯誤百科

元素上的不安全繫結

當 Angular 偵測到對安全性敏感屬性的屬性繫結或特性繫結時,你會看到此錯誤。 Angular 要求這些屬性必須設定為靜態屬性,讓它們的值在元素建立時就設定好,並在元素的整個生命週期中保持不變。錯誤訊息會指出該屬性與元素。

這適用於:

  • 用來設定 <iframe> 安全性模型的屬性:sandbox、allow、allowFullscreen、referrerPolicy、csp、fetchPriority 與 credentialless。它們必須在 src 或 srcdoc 屬性之前套用。
  • 可能改變另一個元素 href 的 SVG 動畫屬性,例如 <animate> 與 <set> 上的 attributeName。

例如,使用屬性繫結時會拋出此錯誤:

<iframe [sandbox]="'allow-scripts'" src="..."></iframe>

或是使用特性繫結時:

<iframe [attr.sandbox]="'allow-scripts'" src="..."></iframe>

另外,在指令的宿主繫結中使用類似模式時,也會拋出此錯誤:

@Directive({
  selector: 'iframe',
  host: {
    '[sandbox]': `'allow-scripts'`,
    '[attr.sandbox]': `'allow-scripts'`,
  },
})
class IframeDirective {}

除錯方式

錯誤訊息包含含有不安全繫結元素的範本所在的元件名稱。

建議的解法是把上述屬性用作靜態屬性,例如:

<iframe sandbox="allow-scripts" src="..."></iframe>

如果你需要讓這些屬性有不同的值(依各種條件而定),你可以使用 @if 或 @switch 控制流程區塊,條件式地渲染適當的 <iframe> 元素:

@if (someConditionA) {
  <iframe sandbox="allow-scripts" src="..."></iframe>
} @else if (someConditionB) {
  <iframe sandbox="allow-forms" src="..."></iframe>
} @else {
  <iframe sandbox="allow-popups" src="..."></iframe>
}