[英]How to dynamically load a template in Angular
我創建了一個新的組件, componentB
使用非常類似的模板作為另一個組件( componentA
)。 當前,當訪問某個url
時,將加載componentA
。 使用新組件時,我想在加載不同的url
時加載略有不同的模板。
componentA
從以下componentA
開始:
@Component({
selector: 'app-reset.app-page.app-page__start',
templateUrl: './reset.component.html',
})
如何使templateUrl
動態化,例如,如果我轉到/url/component-a-route
或/url/component-b-route
,則可以路由相應的模板。 我決定使用一個非常相似的模板將其分為兩個不同的組件,但是最好重用模板並僅更改一些內容。
您應該能夠通過注入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.