【问题标题】:How to use multiple instances of same component in Angular 6?如何在 Angular 6 中使用同一组件的多个实例?
【发布时间】:2018-07-26 03:53:28
【问题描述】:

我创建了一个带有选择器“app-circle”的组件。组件的 HTML 包含一个圆的 SVG。

我想要的是 - 在我的主 HTML 中使用多个“app-circle”来绘制具有不同属性(例如颜色)的多个圆圈。但我似乎无法做到这一点。基本上,我的意图是将“app-circle”重新用作多个对象。

(请原谅我的幼稚;我是 Angular 和 Web 开发的新手,我的经验主要是 C#,这可能是我难以理解 Angular/Web 概念和工作方式的原因)

这里是代码:-

main.html

<div class="diagram-wrapper">
  <app-circle></app-circle>
  <app-circle></app-circle>
</div>

circle.component.html

<svg class="range" height="100" width="100">
  <circle class="circle" cx="50" cy="50" r="40" stroke="black" stroke-width="3" fill="red" />
</svg>

circle.component.ts

import { Component, OnInit, AfterViewInit } from '@angular/core';

@Component({
            selector: 'app-circle',
            templateUrl: './circle.component.html',
            styleUrls: ['./circle.component.scss']
          })
export class CircleComponent implements OnInit, AfterViewInit {

constructor() { }

ngOnInit() { }

ngAfterViewInit() {
 // Circle logic (fill colors, etc.)
}

【问题讨论】:

  • 这应该可以。你能在stackblitz.io 上重现你的问题吗?这可以让我们看到你做错了什么
  • 您需要使用@Input() 来自定义您的角度组件。如果你不使用@Input(),所有实例看起来都一样
  • 阅读更多here
  • @trichetriche 感谢您的回复。这是 stackblitz 的链接: - stackblitz.com/edit/… 这很好用。但是两个圆圈的颜色相同。我想要的是有两个(或更多)具有不同颜色(或其他属性)的圆圈。我想把它做成一个 UI 控件,我可以在不同的地方重复使用它而不会相互影响。
  • @CristianTraìna 感谢您的建议。会试试的。

标签: javascript angular


【解决方案1】:

根据 cmets 中的建议,我在此处将 @Input 添加到您的堆栈闪电战的一个分支中:https://stackblitz.com/edit/angular-jppwhz?file=src%2Fapp%2Fapp.component.html

HTML 使用绑定来绑定所需的颜色:

<div class="diagram-wrapper">
  <app-circle color='blue'></app-circle>
  <app-circle color='green'></app-circle>
</div>

我在颜色值中进行了硬编码,但它们可以作为关联组件的属性提供。

圆圈代码如下所示:

import { Component, OnInit, AfterViewInit, Input, ViewChild, ElementRef } from '@angular/core';

@Component({
  selector: 'app-circle',
  templateUrl: './circle.component.html',
  styleUrls: ['./circle.component.scss']
})
export class CircleComponent implements OnInit, AfterViewInit {
  @Input() color;
  @ViewChild('circle') circleEle: ElementRef;

  constructor() { }

  ngOnInit() { }

  ngAfterViewInit() {
    // Circle logic (fill colors, etc.)
    console.log(this.circleEle);
    if (this.circleEle) {
      this.circleEle.nativeElement.style.fill = this.color;
    }
  }
}

希望这会有所帮助。

【讨论】:

  • 标记为答案。
  • @DeborahK ,我有一个类似的问题,我的所有子组件似乎都共享状态数据。我根据你的演示做了一个演示。我的文件上传更新了最顶层的实例。谢谢stackblitz.com/edit/…
  • 我是否在 stackblitz 中看到您已经解决了您的问题?
  • @AdamMendoza 您是如何解决上传文件时更新最顶层实例的问题的?
  • @Raluca 错误是我在 *ngFor=“logic here”中有一个无关的 name=“myField”,因此数据与转发器中的所有元素相关联。就我而言,我只需要删除标签的名称属性。如果需要名称,则连接一个索引以单独引用每个元素
猜你喜欢
  • 2018-11-21
  • 2018-12-04
  • 1970-01-01
  • 2021-03-31
  • 2017-06-06
  • 2019-06-26
  • 2019-11-11
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多