Angular2按组件替换文本

时间:2016-10-29 20:55:13

标签: angular

我在组件模板中显示文本字符串。

<p>{{ text }}</p>

现在,如果我想替换“#34; candy&#34;通过&#34; apple&#34;在这个文本中自动,例如管道很容易:

<p>{{ text | replaceCandy }}</p>

但是,当我想要更换&#34; candy&#34;通过超链接(HTML)。只有在这样使用时才能使用HTML:

<p [innerHTML]="(text | replaceCandy)"></p>

这已经成为一个问题,因为文本变量可能不安全。所以这不是最好的选择。

如果我想取代&#34; candy&#34;它会变得更复杂。通过我制作的自定义组件:AppleComponent。更换字符串&#34; candy&#34; by&#34;&#34;不起作用。输出为空。

额外信息:我使用管道因为它易于重复使用。虽然不是必需品。只是寻找问题的最佳解决方案。

2 个答案:

答案 0 :(得分:0)

如果要将文本值输入到自定义组件,可以使用如下语法在自定义组件上声明输入值

export class CustomComponent {
    @Input() inputText: string;

然后使用原始HTML中的组件,并使用属性语法对值进行数据绑定:

<p><custom-component [inputText]="text"></custom-component></p>

答案 1 :(得分:0)

您可以使用ngSwitch statement在不同的组件之间进行选择:

<input type="text" [(ngModel)]="text" />
<span [ngSwitch]="text">
  <apple *ngSwitchCase="'apple'"></apple>
  <orange *ngSwitchCase="'orange'"></orange>
  <div *ngSwitchDefault>found no match</div>
</span>

textapple时,将显示apple组件。如果textorange,则会显示orange组件。