将带有 HTML 标签的字符串从父组件传递到子组件

Passing a string with HTML tags from parent to child component

我正在尝试将一个字符串从我的父组件传递到我的子组件。该字符串包含带有 HTML 实体的 HTML 标签。这是父级模板的示例:

<child-component i18n-componentContent="this is a test|for testing" componentContent='my test<sup>&reg;</sup>not working'></child-component>

在子组件方面,我有以下内容:

    @Input() public componentContent: string;
    
...
        public ngOnInit() {
            console.log(this.componentContent);
        }

然而,价值

this.componentContent

是:"my test"

因此,不是整个字符串都传递到子组件中。

为什么不将整个字符串传递给子组件? 将整个字符串从父组件传递到子组件需要做什么?

这不是一个有效的字符串,你需要转义html

componentContent='my test&lt;sup&gt;&reg;&lt;/sup&gt;not working'>

我想,在将字符串从父项传递给子项之前,您正在将 html 标记转换为 html 实体,并且它会生成格式错误的字符串。

相反,您可以执行以下操作:

不要在父组件中转换为 html 实体并使用 encodeURIComponent 函数对父组件中的字符串进行编码,在子组件中使用 decodeURIComponent 解码并在之后在子组件中转换为 html 实体。我希望这样,你可以避免这个问题。

像这样尝试:

以下 html 元素可有效传递到子组件中。

<child-component i18n componentContent='my test<sup>&reg;</sup>not working'></child-component>

如果您在 html 元素和子组件中使用 i18n-componentContent="this is a test|for testing",则获取 my test。所以从 html 元素 i18n-componentContent="this is a test|for testing" 中删除它然后你可以将完整的字符串传递给子组件