如何在Angular中将参数传递给组件的templateUrl?

How to pass a parameter to a component's templateUrl in Angular?

情况是这样的。我有一个 Angular 组件,其 HTML 模板包含对另一个组件的引用。

父组件模板中的部分如下所示:

        <div id="childComponent">
          <!-- Child component should appear here -->
            <child-component></child-component>
        </div>

子组件的定义如下所示:

import { Component, OnInit, Input, Injectable } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
@Component({
    selector: "child-component",
    templateUrl: "ChildComponentController/ChildComponent",
})
export class ChildComponent {
    constructor() {
    }
}

想法是子组件实际上从 ASP.NET 控制器获取其 HTML 模板。问题是“ChildComponentController/ChildComponent”还不够,控制器方法有一个强制输入参数,我们称它为ID。所以我所追求的是这样的:

        <div id="childComponent">
          <!-- Child component should appear here -->
            <child-component [ID]="this.idValue"></child-component>
        </div>
import { Component, OnInit, Input, Injectable } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
@Component({
    selector: "child-component",
    templateUrl: "ChildComponentController/ChildComponent?ID=" + this.ID,
})
export class ChildComponent {
    constructor() {
    }
}

但我不知道是否可以像这样将参数传递给组件的templateUrl。这能以某种方式完成吗?

如果控制器返回的模板没有任何 Angular 绑定,那么这非常简单。基本上您需要对 ChildComponent 进行一些更改并发出 http 请求以将模板作为字符串获取并将其插入 DOM。像这样插入 html 仅当其中没有 Angular 绑定时才有效,因为在运行时没有编译器来编译绑定。另请注意,对于内联模板,'templateUrl' 已更改为 'template'。

import { Component, OnInit, Input, Injectable } from "@angular/core";
import { ActivatedRoute, Router } from "@angular/router";
import { HttpClient } from "@angular/common/http";
import { DomSanitizer, SafeHtml } from "@angular/platform-browser";

@Component({
    selector: "child-component",
    template: '<div [innerHtml]="template"></div>
})
export class ChildComponent {

  @Input() id: string;

  template: SafeHtml;

  constructor(
    private httpClient: HttpClient,
    private domSanitizer: DomSanitizer
  ) {}

  ngOnInit() {
    this.httpClient
      .get(`ChildComponentController/ChildComponent?ID=${this.ID}`, { responseType: "text" 
      }).pipe(take(1))
      .subscribe(data => {
        this.template = this.domSanitizer.bypassSecurityTrustHtml(data);
      });
  }
}

请务必将请求 responseType 设置为文本。如果省略,则 HttpClient 假定响应为 JSON 并将尝试解析它。此外,根据您的要求,您可能想要创建一个 TemplateService 来获取模板并缓存它们。