简体   繁体   English

如何使用变量在 Angular2 中定义 templateUrl

[英]How to use variable to define templateUrl in Angular2

I want the component to set the templateUrl with a variable, but it doesn't work.我希望组件使用变量设置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)
        });
    }

}

Every where I look, I can only see solutions for Angular 1.X, It's really frustrating.每到一个地方,我只能看到 Angular 1.X 的解决方案,这真的很令人沮丧。 I looked into the browser console and figured out that {{article.html}} isn't even resolving.我查看了浏览器控制台,发现 {{article.html}} 甚至没有解析。 It's reading as it is.它正在阅读。 It works totally fine when I set the path myself, so I know that the problem isn't anywhere but here.当我自己设置路径时,它完全正常,所以我知道问题不在任何地方,而是在这里。

I think you should use dynamic component loading to do that.我认为您应该使用动态组件加载来做到这一点。

Let's say we have a json file:假设我们有一个 json 文件:

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

We might create HtmlOutlet directive that will create component dynamicallу with desired templateUrl :我们可能会创建HtmlOutlet指令,该指令将使用所需的templateUrl动态创建组件:

@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(()=>...);;
    });
  }
}

And then use it like:然后像这样使用它:

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

Where html is path to article html其中html是文章 html 的路径

See more details in this Plunkr在此Plunkr 中查看更多详细信息

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

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