模板为&lt;脚本类型=&QUOT;文/ NG模板&QUOT;&GT;用相当于2角 [英] Template as <script type="text/ng-template"> equivalent with angular 2
问题描述
Angularjs(如角1)有寻找一个&LT这种便捷的行为;脚本类型=文/ NG-模板&GT; 元素,它有特定的模板URL的ID请求之前它给服务器。
Angularjs (e.g. angular 1) had this convenient behaviour of searching for a <script type="text/ng-template"> element which had the id of the given template url before requesting it to the server.
例如:下面的code未触发任何附加的http请求
Ex: The code below is not triggering any additional http request
<script type="text/ng-template" id="mytemplate.html">
This is a body for my template
</script>
<script>
//...
app.directive('myComponent', function() {
return {
templateUrl: 'mytemplate.html' // does NOT trigger a http get
};
});
</script>
这似乎并不使用角2工作。
This does not seems to work using Angular 2.
@View({
templateUrl: 'mytemplate.html', // will be fetched from server !
})
class MyComponent{}
有没有实现它的另一种方式?我缺少的东西吗?
Is there another way of achieving it ? Am I missing something ?
的 PS:我不希望我的embbed所有HTML在我的TS文件... 的
推荐答案
如果有人有兴趣,我发现了一个简单的解决方法(一个清洁的解决方案会更好,虽然)
If anyone is interested, i found a simple workaround (a cleaner solution would be better, though)
function template(url, viewdef) {
var elt = document.getElementById(url);
if (elt && elt.getAttribute('type') == 'text/ng-template') {
viewdef.template = elt.innerHTML;
} else
viewdef.templateUrl = url;
return viewdef;
}
@View(template('mytemplate.html', {
directives: [NgIf /*required directives*/]
}))
class MyComponent{}
但是它假定的&lt;脚本&GT;已经是$当该脚本加载p $ psent。
But it assumes that the <script> is already present when this script is loaded.
更好的解决办法
我刚刚想出了一个简单的想法,只是重写 @View
装饰厂。
I just came up with the simple idea to just override the @View
decorator factory.
1)创建一个 viewoverride.ts
文件
import * as ng from 'angular2/core'
let oldNgView = ng.View;
function ViewOverride(viewDef) {
if (typeof viewDef.templateUrl == "string") {
let elt = document.getElementById(viewDef.templateUrl);
if (elt && elt.getAttribute('type') == 'text/ng-template') {
viewDef.template = elt.innerHTML;
delete viewDef.templateUrl;
}
}
return oldNgView(viewDef);
}
ng.View = <ng.ViewFactory>ViewOverride;
的注:把它放在一个单独的独立和文件,迫使其执行是非常重要的先于其他进口的
2),并把这个作为第一引导文件的行:
2) And put this as the first line of your bootstrap file:
import './viewoverride'
3)就是这样。该@View符号现在重写
3) That's it. The @View notation is now overriden
@View({templateUrl:'mytemplate.template'}) class MyClass{}
现在将寻求哪个ID是一个脚本元素 mytemplate.template
will now seek for a script element which id is mytemplate.template
这篇关于模板为&lt;脚本类型=&QUOT;文/ NG模板&QUOT;&GT;用相当于2角的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!