Angular 5 - 使用 InnerHtml 绑定组件选择器
Angular 5 - Bind a component selector with InnerHtml
我有一个名为 "app-component1" 的 component1 选择器。
@Component({
selector: 'app-component1',
templateUrl: './test-widget.component.html',
styleUrls: ['./test-widget.component.scss'] })
所以调用这个组件的html我通常使用:
<app-component1></app-component1>
它工作得很好。
现在从另一个 component2 我有以下变量:
variableToBind = "<app-component1></app-component1>";
并且在组件 2 的 html 中,我使用了以下内容:
<div [innerHtml]="varibableToBind"></div>
html 代码绑定无效。是否有可能帮助我理解原因并可能帮助我找到另一种选择?
Angular 清理 HTML 以防止 XSS 攻击。您应该在控制台输出中找到类似 WARNING: sanitizing HTML stripped some content (see http://g.co/ng/security#xss).
的内容。
有关更多信息,请查看 property binding (esp. content security) and the security docs 上的文档。
根据您的用例,您需要选择其他方法。
您的示例代码不是有效的方法,因为
1) 出于安全原因,html 代码不能直接绑定到元素 属性。参考:https://angular.io/guide/security#xss
2) 在您的情况下,无需为 HTML 执行 属性 绑定。如果你想在 AppComponent2
内部执行不同的逻辑,最好的做法是对可以自定义组件行为的参数进行 属性 绑定:
<div>
<app-component1 [prop1]="myVar1" [prop2]="myVar2"></app-component1>
</div>
然后您可以从组件属性而不是组件本身对其进行自定义。这样会更有意义。
谢谢大家的建议,其实我刚找到答案:
这是行不通的,因为 innerHtml 是在 Angular 编译模板之后呈现的。这意味着它此时不理解您的选择器。
如果你们想要动态加载组件(或任何内容),您应该使用 *ngIf。它对我来说非常好。
如果你真的* 需要将 HTML
传递给组件(例如,如果你的文本带有 <br>
标签或类似的东西),你可以像这样创建自定义 Input
:
export class YourComponent {
@Input() public htmlContent = '';
}
<div [innerHtml]="htmlDescription"></div>
并像这样使用它:
<your-component [htmlDescription]="textWithHtmlTags"></your-component>
* - 例如,如果需要呈现带有基本 HTML
格式标记(如 <b>
、<i>
甚至 <br>
)的文本字符串。
我有一个名为 "app-component1" 的 component1 选择器。
@Component({
selector: 'app-component1',
templateUrl: './test-widget.component.html',
styleUrls: ['./test-widget.component.scss'] })
所以调用这个组件的html我通常使用:
<app-component1></app-component1>
它工作得很好。
现在从另一个 component2 我有以下变量:
variableToBind = "<app-component1></app-component1>";
并且在组件 2 的 html 中,我使用了以下内容:
<div [innerHtml]="varibableToBind"></div>
html 代码绑定无效。是否有可能帮助我理解原因并可能帮助我找到另一种选择?
Angular 清理 HTML 以防止 XSS 攻击。您应该在控制台输出中找到类似 WARNING: sanitizing HTML stripped some content (see http://g.co/ng/security#xss).
的内容。
有关更多信息,请查看 property binding (esp. content security) and the security docs 上的文档。
根据您的用例,您需要选择其他方法。
您的示例代码不是有效的方法,因为
1) 出于安全原因,html 代码不能直接绑定到元素 属性。参考:https://angular.io/guide/security#xss
2) 在您的情况下,无需为 HTML 执行 属性 绑定。如果你想在 AppComponent2
内部执行不同的逻辑,最好的做法是对可以自定义组件行为的参数进行 属性 绑定:
<div>
<app-component1 [prop1]="myVar1" [prop2]="myVar2"></app-component1>
</div>
然后您可以从组件属性而不是组件本身对其进行自定义。这样会更有意义。
谢谢大家的建议,其实我刚找到答案:
这是行不通的,因为 innerHtml 是在 Angular 编译模板之后呈现的。这意味着它此时不理解您的选择器。
如果你们想要动态加载组件(或任何内容),您应该使用 *ngIf。它对我来说非常好。
如果你真的* 需要将 HTML
传递给组件(例如,如果你的文本带有 <br>
标签或类似的东西),你可以像这样创建自定义 Input
:
export class YourComponent {
@Input() public htmlContent = '';
}
<div [innerHtml]="htmlDescription"></div>
并像这样使用它:
<your-component [htmlDescription]="textWithHtmlTags"></your-component>
* - 例如,如果需要呈现带有基本 HTML
格式标记(如 <b>
、<i>
甚至 <br>
)的文本字符串。