如何避免Angular5模板中的部分内容被插值解析?
解决Angular模板中
<pre><code>代码块的特殊字符解析问题 嘿,我刚好碰到过一模一样的问题!Angular会把模板里的{}当成模板表达式来解析,所以你代码块里的类定义直接写在模板里肯定会出问题。给你几个实用的解决方案:
方法1:使用ngNonBindable指令(最推荐)
这个指令能告诉Angular跳过对某个元素及其子元素的模板解析,完美适配代码块的场景。你只需要把它加在<code>或者<pre>元素上就行:
@Component({ providers: [], selector: 'test-component', styles: [], template: ` <h1>Title</h1> <div class="piece-code"> <pre> <code class="javascript" ngNonBindable> export default class Test { say() { console.log('hello world') } } </code> </pre> </div> ` }) export class TestComponent { }
方法2:手动转义特殊字符
如果不想用指令,也可以把代码里的特殊HTML字符和Angular模板字符转义:
{→{}→}<→<>→>
修改后的模板代码会变成这样:
<pre> <code class="javascript"> export default class Test { say() { console.log('hello world') } } </code> </pre>
不过这种方法比较繁琐,代码多的话容易出错,不推荐大量使用。
方法3:将代码放在组件类中(更易维护)
把代码字符串定义在组件类的属性里,然后在模板中插值绑定,这样Angular只会解析插值表达式,不会解析字符串内部的内容:
@Component({ providers: [], selector: 'test-component', styles: [], template: ` <h1>Title</h1> <div class="piece-code"> <pre> <code class="javascript">{{ testCode }}</code> </pre> </div> ` }) export class TestComponent { testCode = `export default class Test { say() { console.log('hello world') } }`; }
这种方法的好处是代码逻辑和模板分离,后期修改代码也更方便,还能避免转义的麻烦。
内容的提问来源于stack exchange,提问作者Howard
相关产品推荐
相关产品推荐

