【问题标题】:Angular data binding sending strings?角度数据绑定发送字符串?
【发布时间】:2020-09-25 06:21:01
【问题描述】:

我是 Angular 新手,我想知道是否有办法将字符串发送到带有变量的 Html 文件?

test.ts

test: string = "Display this {{testText}}";
testText: string = "Success";

test.html

<p>{{test}}</p>

我想要实现的是它显示这个:Display this Success

我只是好奇这是否可能,也许我可以从 API 中检索 HTML 字符串块并像那样显示它们。

【问题讨论】:

  • 我不认为这是可能的,至少不容易。像这样的事情违背了框架的纹理,而不是它。 Angular 旨在以不同的方式实现您的目标。

标签: html angular data-binding


【解决方案1】:

**

这是基本的 Javascript 字符串操作。为此,您的 TypeScript 文件中的 Angular 并没有什么特别之处。

不处理test 上的更新

在 Typescript 文件中,您有两个合并字符串的选项:

第一种方式:

testText: string = "Success";
test: string = `Display this ${this.testText}`;

第二种方式:

testText: string = "Success";
test: string = "Display this " + this.testText;

当然,您可以看到两者都有问题。当您更新您的test 时会发生什么?基于这些方式,testText 只是在创建组件实例时进行初始化,因此如果您想获取您的 test 变量的更改,您应该使用以下方式之一 **

第一种方式:

test.html

<p>Display is {{testText}}</p>
<p>{{'Display is ' + testText}}

第二种方式:

具体来说,您可以创建自定义管道。你应该检查documentation 他们是如何工作的。仅对于这种情况,您不需要使用这种方式。管道通常用于更通用或更复杂的操作。

第三条路:

(more bad than others. Because change detector of Angular will not understand when your content should update the paragraph. You should use others.)

test.ts

getTestText() { return 'Display is ' + this.testText }

test.html

<p>{{ getTestText() }}</p>

**

绑定动态 Html 内容

要绑定任何动态 HTML 模板,您需要使用 innerHTML 属性,例如

&lt;div [innerHTML]="htmlVariable"&gt;&lt;/div&gt;

但这不是一种受信任的方式,因为没有什么可以检查 html 是否受信任或是否有效等。或者如果 html 包含任何组件的选择器,它不会按预期呈现。你应该使用更复杂的方法来做到这一点。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-11-17
    • 1970-01-01
    • 1970-01-01
    • 2019-03-31
    • 2013-10-24
    • 2019-02-26
    • 2020-09-21
    • 1970-01-01
    相关资源
    最近更新 更多