css - 在 Angular 2 中动态设置子项的 css 属性

标签 css ionic-framework angular ionic2

我正在努力使用 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/

相关文章:

html - 如何让div跳一行

ionic-framework - 如何在 Ionic 3 中集成 PayUMoney Gate 方式?

android - 在没有 photoshop 知识的情况下创建简单的启动画面(Ionic/Cordova)

Angular 2 Ngrx 商店、效果和 "Ephemeral States"

angular - 请为 APP_BASE_HREF token 异常 Angular2 提供一个值

javascript - 在 Angularjs 指令中将 CSS 样式与模板分开

html - 我的 CSS 悬停来更改按钮的背景颜色不起作用

css - 使用 animate.css 关闭引导模式

node.js - 无法启动新的 ionic 项目

javascript - 在 Angular cli 中配置代理