Abh*_*h.M 5 javascript angular
我创建了一个带有选择器“app-circle”的组件。组件的 HTML 包含一个圆的 SVG。
我想要的是 - 在我的主 HTML 中使用多个“app-circle”来绘制具有不同属性(例如颜色)的多个圆圈。但我似乎无法做到这一点。基本上,我的目的是将“app-circle”重新用作多个对象。
(请原谅我的幼稚;我是 angular 和 web 开发的新手,我的经验主要是在 C# 中,这可能是我在环绕 angular/web 概念和工作方式时发现困难的原因)
这是代码: -
主文件
<div class="diagram-wrapper">
<app-circle></app-circle>
<app-circle></app-circle>
</div>
Run Code Online (Sandbox Code Playgroud)
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>
Run Code Online (Sandbox Code Playgroud)
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.)
}
Run Code Online (Sandbox Code Playgroud)
按照评论中的建议,我将 @Input 添加到您的 stackblitz 的分支: 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>
Run Code Online (Sandbox Code Playgroud)
我对颜色值进行了硬编码,但它们可以作为关联组件的属性提供。
循环代码如下所示:
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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
希望这可以帮助。