首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >Angular2-5通用指令在html元素上呈现不同的样式

Angular2-5通用指令在html元素上呈现不同的样式
EN

Stack Overflow用户
提问于 2018-03-06 16:45:33
回答 1查看 610关注 0票数 1

我正在编写Angular5应用程序,其中我是动画对象的基础上,不同的顶部和左边位置。

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

我的animation.compoenent.ts像这样设置样式

代码语言:javascript
复制
this.styles = { 'transform':'translate(0px,0px)', 'position': 'absolute', 'top': top+'px', 'left': left+'px' };

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

我的animation.component.html看起来就像

代码语言:javascript
复制
<div class="parent-container">
     <div [ball1Style] = "ball1StyleChange">Child1</div>
     <div [ball2Style] = "ball2StyleChange">Child1</div>
     <div [ball3Style] = "ball3tyleChange">Child1</div>
</div>

我写了3条指令来处理这3种不同的儿童div的造型。下面是我的一个ball1directive是什么样的

代码语言:javascript
复制
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通用。

分享你的想法,会很有帮助的。谢谢苏海布

EN

回答 1

Stack Overflow用户

发布于 2018-03-06 19:36:28

基于你在这里所拥有的,我不认为这个指令是必要的,因为已经有一个由角度小组提供的指令,它可以满足你的需要。您应该能够使用ngStyle异步管道

代码语言:javascript
复制
<div class="parent-container">
    <div [ngStyle]="ball1StyleChange | async">Child1</div>
    <div [ngStyle]="ball2StyleChange | async">Child2</div>
    <div [ngStyle]="ball3StyleChange | async">Child3</div>
</div>
票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/49135965

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档