如何使用变量在 Angular2 中定义 templateUrl [英] How to use variable to define templateUrl in Angular2

查看:19
本文介绍了如何使用变量在 Angular2 中定义 templateUrl的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我希望组件使用变量设置 templateUrl,但它不起作用.

I want the component to set the templateUrl with a variable, but it doesn't work.

@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 的解决方案,这真的很令人沮丧.我查看了浏览器控制台,发现 {{article.html}} 甚至没有解析.它正在阅读.当我自己设置路径时,它工作得很好,所以我知道问题不在任何地方,而是在这里.

Every where I look, I can only see solutions for Angular 1.X, It's really frustrating. I looked into the browser console and figured out that {{article.html}} isn't even resolving. 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.

假设我们有一个 json 文件:

Let's say we have a json file:

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

我们可能会创建 HtmlOutlet 指令,该指令将使用所需的 templateUrl 动态创建组件:

We might create HtmlOutlet directive that will create component dynamicallу with desired 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(()=>...);;
    });
  }
}

然后像这样使用它:

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

其中 html 是文章 html 的路径

Where html is path to article html

在此Plunkr

See more details in this Plunkr

这篇关于如何使用变量在 Angular2 中定义 templateUrl的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆