我正在尝试分解更大的 HTML 块,这些块具有基于标志的重复标记。
有没有办法让 html 代码分成文件 one.html、two.html 并将它们渲染到我的组件中(.ts 将决定加载哪个 html)
基本思想是 一个组件 -> 多个 html 文件
我可以像以前一样拥有单个大 html 并使用 ng-template/ngContentOutlet,但这仍然使 html 上 2k+ 行的可读性成为问题。
我们使用的是 Angular 18.x 独立版本,任何建议都是宝贵的
AngularJS
ng-include
不完全是,而是被 Angular 的 ng-template/ngContentOutlet
取代。
您可以创建一个专门设计用于容纳
reusable ng-templates
的组件。
该组件将包含其 HTML 中的所有模板以及每个模板的 ViewChild。
@Component({ ... })
export class ReusableTemplatesComponent {
@ViewChild('test') test!: TemplateRef<any>;
}
<ng-template #test let-str="str">
{{str}} World!
</ng-template>
然后当你想使用这些模板时,将组件添加到底部并使用模板引用创建引用,访问模板并传递上下文。
<ng-container *ngTemplateOutlet="reusableTemplates.yesNoFlagTemplate;
context:{str: 'Hello'}"></ng-container>
....
<app-reusable-templates #reusableTemplates/>