【问题标题】:How to render a component through the id is stored in variable?如何通过将 id 存储在变量中来渲染组件?
【发布时间】:2020-02-26 19:25:56
【问题描述】:

我有两个组件。 1. App 组件,2. 子组件。

为了更好地理解,代码和输出在 stackblitz 中:https://stackblitz.com/edit/angular-j9cwzl

app.component.ts:

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  template: `
    <div id="child"></div>
    <div id="{{childComponent}}"></div>
  `
})
export class AppComponent  {
  childComponent='child';
}

child.component.ts

import { Component } from '@angular/core';

@Component({
  selector: '[id=child]',
  template: '<div>I am child</div>'
})
export class ChildComponent  { }

当我直接在 App 组件的模板中写入子组件的 id 时,它可以很好地呈现。但是当我通过变量写入子组件的 id 时,它只是创建了一个 id="child" 的 div 元素。

我的问题是为什么会这样?如何通过脚本文件中的变量动态呈现带有id的孩子?

【问题讨论】:

标签: javascript html angular typescript


【解决方案1】:

我有一个建议,为什么您的插值 {{ childComponent }} 不起作用。在我看来,Angular 的工作顺序如下:

  • 首先,它会查看您的所有 HTML,然后尝试查找可以评估为 componentdirective 的属性或选择器

  • 那么第二步就是当我们找到一个组件或者指令的时候,再应用{{ }}插值

所以也许这就是为什么你的插值没有在你的选择器中评估的原因。因为选择器的评估已经完成,然后指令的评估开始了。

如果你想决定应该渲染什么组件,那么你可以使用*ngIf声明:

<ng-container *ngIf="childComponentl else anotherComponent">
    <div id="child"></div>
</ng-container>    
<ng-template #anotherComponent>
    test
</ng-template>

打字稿:

childComponent='"child1"';

更新:

如果你想避免硬编码,那么你可以动态加载组件:

【讨论】:

  • 我不想硬编码选择器 ID。我希望它通过一个变量来呈现它。
猜你喜欢
  • 2017-06-03
  • 2019-06-05
  • 1970-01-01
  • 2017-03-18
  • 2021-10-03
  • 2016-04-22
  • 2020-11-19
  • 1970-01-01
  • 2015-08-19
相关资源
最近更新 更多