我正在努力使用 ngStyle
在 angular 2 中设置子标签的 css 属性指令。
我不确定我尝试将其应用于 SVG 是否会使它复杂化。
现状
我有一个微调器,是这样实现的:
<ion-spinner name="bubbles"></ion-spinner>
选择器来自ionic framework .
我目前的代码是:
@Component({
selector: 'some-selector',
template: `
<ion-spinner name="bubbles"></ion-spinner>
`
})
export class SomeComponent {
private someColour: string = "red"
}
我知道我可以使用组件导向器中的样式数组来影响 css 样式(尽管由于封装(我认为)它必须进入它自己的 css 样式表,而不是组件的样式,否则它只影响某些属性),我还可以使用 ngStyle 属性来设置动态 css 样式。然而,元素在 html 中是这样出现的:
<ion-spinner name="bubbles" class="spinner-bubbles">
<!--template bindings={}-->
<svg viewBox="0 0 64 64" style="top: 0px; left: 9px; animation-delay: -1000ms; animation-duration: 1000ms;">
<circle transform="translate(32,32)" r="5"></circle>
</svg>...
</ion-spinner>
并且 css 需要影响 'circle' 标签。我知道我可以使用的 css 是:
ion-spinner {
* {
fill: blue;
}
&.spinner-circles circle,
&.spinner-bubbles circle,
&.spinner-dots circle {
fill: blue;
}
}
由于微调器有气泡,但是:
如何让选择器内部的颜色变化动态化?
我正在使用 Angular “2.0.0-rc.1”
最佳答案
它不是 Angular 世界中的最佳选择,但如果 ion-spinner
不为内部 <circle>
提供任何类型的“钩子(Hook)”元素,你可以引用他们的 HTMLElement
实例(通过 DOM)并进行操作,例如向它们添加类:
import { Component, ViewChild, ContentChild, ElementRef } from '@angular/core';
import { Spinner } from 'ionic?';
@Component({
selector: 'some-selector',
template: `
<ion-spinner name="bubbles"></ion-spinner>
`,
directives: [Spinner]
})
export class SomeComponent {
@ViewChild(Spinner, {read: ElementRef}) spinnerEl: ElementRef;
ngAfterViewInit() {
console.log("Spinner ElementRef: ", this.spinnerEl);
console.log("Spinner ElementRef.nativeElement: ", this.spinnerEl.nativeElement);
this.addClassForAllCirclesInsideElement(this.spinnerEl.nativeElement, "someClass");
}
addClassForAllCirclesInsideElement(nativeElement, classNameToAdd) {
// direct DOM manipulation...
let circles = nativeElement.querySelectorAll('circle');
circles.forEach((circle) => { circle.className += " " + classNameToAdd; })
}
}
关于css - 在 Angular 2 中动态设置子项的 css 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38042808/