Angular2-5 Generic Directive用于在html元素上呈现不同的样式

问题描述 投票:1回答:1

我正在编写Angular5应用程序,我根据不同的顶部和左侧位置动画对象。

我有一个父div,我成功地动画了3个子div元素。问题:我的代码适用于固定数量的子div,但我需要让它适用于任意数量的子div。

我的animation.component.ts设置了这样的样式

this.styles = { 'transform':'translate(0px,0px)', 'position': 'absolute', 'top': top+'px', 'left': left+'px' };

this.ballStyleChange = new  BehaviorSubject<any>(this.styles);

我的animation.component.html看起来像

<div class="parent-container">
     <div [ball1Style] = "ball1StyleChange">Child1</div>
     <div [ball2Style] = "ball2StyleChange">Child1</div>
     <div [ball3Style] = "ball3tyleChange">Child1</div>
</div>

我已经编写了3个指令来处理这3个不同的Child div的样式。这是我的ball1directive之一的样子

import { Directive, ElementRef, Renderer, Input, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
import { PlayerStyle } from '../Models/PlayerStyle';
@Directive({ selector: '[ballStyle]' })
export class StyleDirective implements OnInit{
@Input() ballStyle: Observable<any>;  
constructor(public el: ElementRef,public renderer: Renderer) {
}
ngOnChanges()
{
    this.ballStyle.subscribe(
        result=>
        {               
            let style = "transform:"+result.transform+"; position: absolute; 
     top:"+ result.top+ "; left:"+result.left +";";
            this.renderer.setElementProperty(this.el.nativeElement, 'style', 
    style);               
        });
}
   ngOnInit(){      
   }
}


import { Directive, ElementRef, Renderer, Input, OnInit } from '@angular/core';
import { Observable } from 'rxjs/Observable';
@Directive({  selector: '[ball1Style]'})
export class Ball12Directive implements OnInit {  
@Input() ball1Style: Observable<any>;
constructor(public el: ElementRef,public renderer: Renderer) { }
ngOnInit() { }
   ngOnChanges()
   {        
        this.ball1Style.subscribe(
        result=>
        {
            let style = "transform:"+result.transform+"; position: absolute; top:"+ result.top+ "; left:"+result.left +";";
            this.renderer.setElementProperty(this.el.nativeElement, 'style', style);               
        });
    }
}

所以这些是我的3个指令中的两个,现在问题是我的所有子div都将向不同的方向移动,我需要使用一个指令处理所有这些指令,以使其对任意数量的子div都是通用的。

分享你的想法,会非常有帮助。谢谢Sohaib

angular rxjs observable angular-directive
1个回答
0
投票

基于你在这里所拥有的,我不认为该指令是必要的,因为Angular团队已经提供了你需要的指令。你应该能够使用ngStyleasync pipe

<div class="parent-container">
    <div [ngStyle]="ball1StyleChange | async">Child1</div>
    <div [ngStyle]="ball2StyleChange | async">Child2</div>
    <div [ngStyle]="ball3StyleChange | async">Child3</div>
</div>
© www.soinside.com 2019 - 2024. All rights reserved.