简体   繁体   English

如何在Angular中动态加载模板

[英]How to dynamically load a template in Angular

I have created a new component, componentB that uses a very similar template as another component ( componentA ). 我创建了一个新的组件, componentB使用非常类似的模板作为另一个组件( componentA )。 Currently, when a certain url is accessed, the componentA is loaded. 当前,当访问某个url时,将加载componentA With the new component, I want to load a slightly different template when a different url is loaded. 使用新组件时,我想在加载不同的url时加载略有不同的模板。

componentA starts with the following: componentA从以下componentA开始:

@Component({
  selector: 'app-reset.app-page.app-page__start',
  templateUrl: './reset.component.html',
})

How can I make the templateUrl dynamic, such that if I go to /url/component-a-route or /url/component-b-route , I can route the corresponding template. 如何使templateUrl动态化,例如,如果我转到/url/component-a-route/url/component-b-route ,则可以路由相应的模板。 I decided to split this into two different components with a very similar template, but it would be better to reuse the template and just change a few bits. 我决定使用一个非常相似的模板将其分为两个不同的组件,但是最好重用模板并仅更改一些内容。

You should be able to solve this by injecting Angular router and checking the current page url to inject a dynamic string into your template url: 您应该能够通过注入Angular路由器并检查当前页面的url来向模板url注入动态字符串来解决此问题:

import { Component } from '@angular/core';
import { Router } from '@angular/router';

@Component({
    selector: 'app-reset.app-page.app-page__start',
    template: '{{path}}/reset.component.html'
})
export class Component {
    public path: string = "";

    constructor(private router: Router) {}

    ngOnInit() {
        this.path = this.router.url.indexOf('urlA') >= 0 ? 'pathA' : 'pathB';
    }
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM