如何在Angular 6中使用同一组件的多个实例?

时间:2018-07-25 12:51:04

标签: javascript angular

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

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

(请原谅我太幼稚;我是angular&web开发的新手,我的经验主要是C#,这可能是我难以解决有关angular / web概念和工作方式的原因)< / p>

这是代码:-

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.)
}

1 个答案:

答案 0 :(得分:0)

根据评论中的建议,我将@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;
    }
  }
}

希望这会有所帮助。

相关问题