如何从带有angular2和Typescript的HTMLElement获取样式值

时间:2016-08-05 13:04:02

标签: angular directive angular2-template angular2-directives

是否可以读出HTMLElement中的值?

以下代码正在运行,但它在向后转换中有一个小延迟。多数民众赞成我需要_target元素的高度值。

import {
Directive, Input, Renderer, OnInit, ElementRef, TemplateRef
} from '@angular/core';

@Directive({
selector: '[accordion]'

})
export class AccordionDirective implements OnInit{
   private _listener:Function;
   private _active = false;
   private _height;

   @Input('accordion') _target:HTMLElement;

   constructor(private _renderer:Renderer,
               private element:ElementRef) {
   }

   ngOnInit() {

    this._renderer.setElementStyle(this._target, 'max-height', '0em');
    this._renderer.setElementClass(this._target, 'slider', true); // set css transition to the target element

    this._listener = this._renderer.listen(this.element.nativeElement, 'click', () => {

        if(!this._active){
            this._renderer.setElementStyle(this._target, 'max-height', '50em'); <-- here is the variable height needed
        }else{
            this._renderer.setElementStyle(this._target, 'max-height', '0em');
        }
        this._active = !this._active;
        });
     }
   }

2 个答案:

答案 0 :(得分:1)

解决这个问题的方法。

import {
  Directive, Input, Renderer, OnInit, ElementRef, TemplateRef
} from '@angular/core';

@Directive({
  selector: '[accordion]'

})

export class AccordionDirective implements OnInit{
  private _listener:Function;
  private _active = false;
  private _height;
  private _maxHeight;

  @Input('accordion') _target:HTMLElement;

  constructor(private _renderer:Renderer,
           private element:ElementRef) {}

  ngOnInit() {
  this._maxHeight = this._target.scrollHeight;
  this._renderer.setElementStyle(this._target, 'max-height', '0em');
  this._renderer.setElementClass(this._target, 'slider', true);

  this._listener = this._renderer.listen(this.element.nativeElement, 'click', () => {

    if(!this._active){
        this._renderer.setElementStyle(this._target, 'max-height', this._maxHeight + 'px');
    }else{
        this._renderer.setElementStyle(this._target, 'max-height', '0em');
    }
    this._active = !this._active;
    });
  }
}

答案 1 :(得分:-2)

使用ngClass / ngStyle添加&amp;删除类/样式