【问题标题】:Multiple instances of the same Angular 6 component同一个 Angular 6 组件的多个实例
【发布时间】:2018-11-21 15:14:08
【问题描述】:

我正在构建一个仪表板,显示来自包含各种服务器信息的大型 JSON 对象的数据。在仪表板中,我将有 12 个方块,其中包含完全相同的信息,但来源不同(CPU 使用情况、内存使用情况、错误列表等)。

所以我想知道是否可以动态构建一个接受参数的组件,例如 3 个数字和一个字符串,例如 ram、cpu、电源和 IP 地址(实际情况接近 20 个不同的数据点) ,然后使用 Angular 6 组件在 init 上复制它,但将不同的数据传递给同一组件的 12 个不同实例中的每一个。我假设使用 Bootstrap 我可以使用网格格式化大小和位置。

一个简单的例子将不胜感激!

【问题讨论】:

  • 或类似 `
  • 我投了赞成票,因为我认为这是一个有效的问题。但是我认为,如果您浏览英雄之旅,您可能会对如何解决这个问题有所了解:-)

标签: angular typescript components


【解决方案1】:

您可以定义您的组件以将所需的属性作为输入,并使用不同的输入多次重复使用相同的组件。

在下面的示例中,您使用name 属性定义HelloComponent,使用不同的输入初始化HelloComponent 的多个实例。

儿童

export class HelloComponent  {
  @Input() name: string;
}

家长

<hello name="Ben"></hello>
<hello name="Jack"></hello>
<hello name="Roger"></hello>

Demo

【讨论】:

  • 这个问题是,当你在 html 中使用单选按钮之类的东西时,“name”属性会被转移到另一个相同类型的组件中
【解决方案2】:

app.component.html

<data-component [cpu]="cpu" [usage]="usage" [otherData]="otherData"></data-component>
<data-component [cpu]="cpu1" [usage]="usage1" [otherData]="otherData1"></data-component>
<data-component [cpu]="cpu2" [usage]="usage2" [otherData]="otherData2"></data-component>
<data-component [cpu]="cpu3" [usage]="usage3" [otherData]="otherData3"></data-component>
<data-component [cpu]="cpu4" [usage]="usage4" [otherData]="otherData4"></data-component>

app.component.ts

在这里,您可以对从不同端点获取的所有 cpu、使用情况、其他数据值进行逻辑并进行初始化。

data.component.html

//你的卡片逻辑。

同样,您可以通过模型通过app.component.ts 控制组件的各种实例。

【讨论】:

    猜你喜欢
    • 2018-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-11-11
    • 1970-01-01
    • 2023-03-23
    • 1970-01-01
    • 2022-10-26
    相关资源
    最近更新 更多