我想像这样动态加载角度模板:
import { getHTMLTemplate } from './util';
const dynamicTemplate = getHTMLTemplate();
@Component({
selector: 'app-button',
// templateUrl: './button.component.html',
template: `
<div">
some div
</div>
${dynamicTemplate}
`,
styleUrls: ['./button.component.less'],
})
getHTMLTemplate
执行:
export function getHTMLTemplate(){
return `<div>dynamic div</div>`;
};
这适用于ng serve
,但失败了ng build
.
它抛出以下错误:
src/util.ts(5,32): Error during template compile of 'AppComponent'
Function calls are not supported in decorators but 'getHTMLTemplate' was called.
Angular 旨在以不同的方式实现 OP 所追求的目标。
您可以在包含 HTML 字符串的组件上创建一个属性。
然后,您可以在组件模板中使用“moustache”来插入字符串:
<div innerHtml="{{propertyName}}"></div>
您还可以使用属性绑定:<div [innerHtml] = "propertyName"></div>
如果字符串是动态传入的,则需要使用属性绑定选项,并注入 DOMSanitizer 以引入包含样式标签的 html。
DOMSanitizer 有一些可用的方法(在“@angular/platform-browser”中找到)用于返回安全的 html、脚本、样式和其他一些方法。
希望这可以帮助
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)