Javascript Angular2 动态模板或 ng-include
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/39328215/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
Angular2 dynamic template or ng-include
提问by nCore
Is there a way to load templates dynamically in angular2? In angular1 I used ng-include to load different html
template in the main controller view. I know that angular2 can only take 1 templateUrl and been googling ng-include
in angular2 and can't find any reference.
有没有办法在 angular2 中动态加载模板?在 angular1 中,我使用 ng-includehtml
在主控制器视图中加载不同的模板。我知道 angular2 只能使用 1个 templateUrl 并且一直ng-include
在 angular2 中搜索并且找不到任何参考。
回答by siddharthrc
Why do you need ng-include when you can make the html as a custom new component and use it wherever you need it, thanks to the selector tag.
多亏了选择器标签,当您可以将 html 作为自定义新组件并在任何需要的地方使用它时,为什么还需要 ng-include。
Eg:
例如:
@Component({
selector: 'app-my-component',
templateUrl: './my-component.component.html'
})
So here, the my-component.component.html
file can have the markup you want to include or show everywhere else.
and the selector tag value <app-my-component></app-my-component>
can be used throughout your application markup html files(you can think of it as your everyday html tags--but highly customized in nature and interpreted by the angular framework first aka custom tags but built using angular).
因此,在这里,my-component.component.html
文件可以包含您想要包含或在其他任何地方显示的标记。并且选择器标记值<app-my-component></app-my-component>
可以在整个应用程序标记 html 文件中使用(您可以将其视为日常的 html 标记——但本质上是高度定制的,并且首先由 angular 框架解释,即自定义标签,但使用 angular 构建)。
回答by tibbus
Not sure about the dynamic template, but you can insert a dynamic component (which ofcourse will have a different template) .
不确定动态模板,但您可以插入动态组件(当然会有不同的模板)。
A simple example, but deprecated can be found here : Angular2: Insert a dynamic component as child of a container in the DOM
一个简单的例子,但这里已经弃用了:Angular2: Insert a dynamic component as a child of a container in the DOM
An up to date example, but more complex can be found here : How can I use/create dynamic template to compile dynamic Component with Angular 2.0?
一个最新的例子,但更复杂的可以在这里找到:How can I use/create dynamic template to compile dynamic Component with Angular 2.0?