如何使用variables在Angular2中定义templateUrl

我希望组件使用variables来设置templateUrl ,但它不起作用。

 @Component({ selector: 'article', templateUrl: '{{article.html}}', styleUrls: ['styles/stylesheets/article.component.css'] }) export class ArticleComponent implements OnInit { constructor(private route: ActivatedRoute, private articleService: ArticleService) { } articleArray = this.articleService.getArticles(); article: Article; ngOnInit(): void { this.route.params.forEach((params: Params) => { let headline = params['headline']; this.article = this.articleService.getArticle(headline) }); } } 

无论我在哪里看,我只能看到Angular 1.X的解决scheme,这真是令人沮丧。 我查看了浏览器控制台,发现{{article.html}}甚至没有解决。 它正在阅读。 当我自己设定path的时候,它是完全正常的,所以我知道问题不在这里。

我想你应该使用dynamic组件加载来做到这一点。

假设我们有一个json文件:

 { "title": "My first article", "html": "app/articles/first.html" } 

我们可能会创buildHtmlOutlet指令,该指令将用所需的templateUrldynamic创build组件:

 @Directive({ selector: 'html-outlet' }) export class HtmlOutlet { @Input() html: string; constructor(private vcRef: ViewContainerRef, private compiler: Compiler) {} ngOnChanges() { const html = this.html; if (!html) return; @Component({ selector: 'dynamic-comp', templateUrl: html }) class DynamicHtmlComponent { }; @NgModule({ imports: [CommonModule], declarations: [DynamicHtmlComponent] }) class DynamicHtmlModule {} this.compiler.compileModuleAndAllComponentsAsync(DynamicHtmlModule) .then(factory => { const compFactory = factory.componentFactories .find(x => x.componentType === DynamicHtmlComponent); const cmpRef = this.vcRef.createComponent(compFactory, 0); cmpRef.instance.prop = 'test'; cmpRef.instance.outputChange.subscribe(()=>...);; }); } } 

然后像这样使用它:

 <html-outlet [html]="article?.html"> 

其中html是文章html的path

在这个普朗克看到更多的细节