[英]Dynamically load Angular template in `Component` decorator
I want to load angular template dynamically like this:我想像这样动态加载角度模板:
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
implementation: getHTMLTemplate
实现:
export function getHTMLTemplate(){
return `<div>dynamic div</div>`;
};
This works fine on ng serve
, but fails on ng build
.这在ng serve
上工作正常,但在ng build
上失败。
It throws following error:它抛出以下错误:
src/util.ts(5,32): Error during template compile of 'AppComponent'
Function calls are not supported in decorators but 'getHTMLTemplate' was called.
Angular is designed to achieve what the OP is after in a different way. Angular 旨在以不同的方式实现 OP 所追求的目标。 You can create a property on the component which contains the HTML string.您可以在包含 HTML 字符串的组件上创建一个属性。 You can then use 'moustaches' in the component's template interpolate the string:然后,您可以在组件的模板中使用 'moustaches' 插入字符串:
<div innerHtml="{{propertyName}}"></div>
You can also use property binding: <div [innerHtml] = "propertyName"></div>
您还可以使用属性绑定: <div [innerHtml] = "propertyName"></div>
If the string is coming in dynamically, you will need use the property binding option, and inject DOMSanitizer to bring in html containing style tags.如果字符串是动态传入的,则需要使用属性绑定选项,并注入 DOMSanitizer 以引入包含样式标签的 html。
DOMSanitizer has a few methods available (found in '@angular/platform-browser') for returning safe html, scripts, styles and some others. DOMSanitizer 有一些可用的方法(在“@angular/platform-browser”中找到)用于返回安全的 html、脚本、样式和其他一些方法。
Hope this helps希望这可以帮助
As error says, use function not the function expression:正如错误所说,使用函数而不是函数表达式:
getHTMLTemplate
implementation: getHTMLTemplate
实现:
export const getHTMLTemplate = () => {
return `<div>dynamic div</div>`;
};
To Be:成为:
export const getHTMLTemplate() {
return `<div>dynamic div</div>`;
};
Without holding the function ref in a const
( source ) Try:如果不将函数 ref 保存在const
( source ) 中,请尝试:
export function getHTMLTemplate() {
return `<div>dynamic div</div>`;
};
@Component({
selector: 'app-button',
// templateUrl: './button.component.html',
template: `
<div">
some div
</div>
${getHTMLTemplate()}
`,
styleUrls: ['./button.component.less'],
})
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.