[英]How to use multiple instances of same component in Angular 6?
我创建了一个带选择器'app-circle'的组件。 组件的HTML包含一个圆的SVG。
我想要的是 - 在我的主HTML中使用多个'app-circle'来绘制具有不同属性(例如,颜色)的多个圆圈。 但我似乎无法做到这一点。 基本上,我的意图是将'app-circle'重新用作多个对象。
(请原谅我天真;我是角色和网络开发的新手,我的经验主要是在C#中,这可能是我找到缠绕角/网概念和工作方式的困难的原因)
这是代码: -
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.)
}
根据评论中的建议,我在这里将@Input添加到你的stackblitz的一个分支: https ://stackblitz.com/edit/angular-jppwhz ? file = ssc %%Fapp%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;
}
}
}
希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.