【问题标题】:How to use variable to define templateUrl in Angular2如何在Angular2中使用变量定义templateUrl
【发布时间】:2016-09-09 11:17:04
【问题描述】:

我希望组件用变量设置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 的解决方案,真是令人沮丧。我查看了浏览器控制台,发现 {{article.html}} 甚至没有解决。它按原样阅读。当我自己设置路径时它工作得很好,所以我知道问题不在于这里。

【问题讨论】:

  • 不知道有没有可能!

标签: angular typescript


【解决方案1】:

我认为你应该使用动态组件加载来做到这一点。

假设我们有一个 json 文件:

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

我们可能会创建 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(()=>...);;
    });
  }
}

然后像这样使用它:

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

html 是文章 html 的路径

在此Plunkr

中查看更多详细信息

【讨论】:

  • 你太棒了!非常感谢,这为我省去了很多麻烦!
  • 尝试使用它时,它不会解析为 htmlUrl,而只是 html。我从你的 plunkr 复制了确切的部分。
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2023-04-04
  • 1970-01-01
  • 1970-01-01
  • 2016-08-17
  • 2016-06-12
  • 2023-03-09
相关资源
最近更新 更多