[英]How to use multiple instances of same component in Angular 6?
I have created a component with selector 'app-circle'. 我创建了一个带选择器'app-circle'的组件。 The HTML of the component contains an SVG for a circle.
组件的HTML包含一个圆的SVG。
What I want is - to use multiple 'app-circle' in my main HTML to draw multiple circles with different attributes (say, color). 我想要的是 - 在我的主HTML中使用多个'app-circle'来绘制具有不同属性(例如,颜色)的多个圆圈。 But I cannot seem to be able to do this.
但我似乎无法做到这一点。 Basically, my intention was to re-use 'app-circle' as multiple objects.
基本上,我的意图是将'app-circle'重新用作多个对象。
(Please forgive me for being naive; I am new to angular & web development and my experience is mainly in C#, which might be the reason for me to find difficulty in wrapping around angular/web concepts and way of working) (请原谅我天真;我是角色和网络开发的新手,我的经验主要是在C#中,这可能是我找到缠绕角/网概念和工作方式的困难的原因)
Here is the code: - 这是代码: -
main.html main.html中
<div class="diagram-wrapper">
<app-circle></app-circle>
<app-circle></app-circle>
</div>
circle.component.html 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 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.)
}
Following the suggestion in the comments, I added the @Input to a fork of your stackblitz here: https://stackblitz.com/edit/angular-jppwhz?file=src%2Fapp%2Fapp.component.html 根据评论中的建议,我在这里将@Input添加到你的stackblitz的一个分支: https ://stackblitz.com/edit/angular-jppwhz ? file = ssc %%Fapp%2Fapp.component.html
The HTML uses binding to bind the desired color: HTML使用绑定来绑定所需的颜色:
<div class="diagram-wrapper">
<app-circle color='blue'></app-circle>
<app-circle color='green'></app-circle>
</div>
I hard-coded in the color values, but they could be provided as properties from the associated component. 我在颜色值中进行了硬编码,但它们可以作为相关组件的属性提供。
The circle code then looks like this: 然后圆圈代码如下所示:
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;
}
}
}
Hope this helps. 希望这可以帮助。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.