【问题标题】:Angular 2 Host Listener Change div heigthtAngular 2 Hostlistener 更改 div 高度
【发布时间】:2017-06-12 19:04:51
【问题描述】:

我在过去几个小时阅读了有关 Angular 2 中事件侦听器的信息,但我认为那里严重缺乏文档。

我想将不同 div 组(在 ngFor 中创建)的高度设置为具有最大高度的组。有点像Angular 1 example

我知道范围和$watch 不再存在。所以我尝试用 Host Listener 来做,但我找不到任何好的文档。有很多关于事件"click""mouseover" 等的教程。但没有其他可能的事件。我需要像 $watch 或 onChange 这样的东西。 (没有输入字段,基本元素)基本上任何有关可能事件名称的文档都会有所帮助。

最终在angular2中也有上述链接的例子。

PS:找到 'window: resize''div: resize' 不工作。

编辑:在 maximus 的帮助下,我完成了,这是工作代码。

创建了一个指令文件:

cmets.directive.ts

import { Directive, ElementRef, Input } from '@angular/core';
import { DoCheck } from '@angular/core';

@Directive({ selector: '[comments]' })

export class CommentsDirective implements DoCheck{

    style: any;

    constructor(private element: ElementRef) {

    }

    ngDoCheck() {
        console.log(this.element);
        this.style = { //scope variable style, shared with our controller
            height:this.element.nativeElement.offsetHeight+'px', //set the height in style to our elements height
            width:this.element.nativeElement.offsetWidth+'px' //same with width
        };
    }
}

比我刚刚在 NG-Module 中导入它。

HTML 部分:

<div comments [ngStyle]="style">

如果我完成了使所有高度相等的部分,基于最大的,我会更新它。

【问题讨论】:

  • 你看过mutationobservers - developer.mozilla.org/en/docs/Web/API/MutationObserver 吗?
  • 您不太可能想要或不需要这样做。本质上,您正在尝试管理页面布局,但这是 HTML 和 CSS 的工作。如果你能提供一个简单的例子来说明你想要做什么,我相信这里有人可以帮助你展示如何在 CSS 中做到这一点。
  • @torazaburo 我知道这通常是 css 的一部分,在正常情况下很容易使用例如。弹性盒。在我的情况下,页面布局非常基于检索我从数据库中检索的数据。所以我必须根据接收的元素更改布局。示例:3 列,每列包含 cmets、news 和其他内容(在单独的行中)。根据 cmets 最多的块,所有的评论框高度应该相同。
  • 他们没有相同的父母。无论如何都可以不用担心。

标签: javascript css angular


【解决方案1】:

我知道 scope 和 $watch 已经不存在了

Angular.js 在运行摘要时触发观察者。 Angular 也有类似的东西,它在运行摘要时触发 ngDoCheck。阅读更多here

以您为Angular.js 显示的示例进行类比,您可以在 Angular 中按照以下方式做一些事情:

@Directive({
   selector: '[HeightSetter]'
})
class HeightSetter {
   style: any;

   constructor(private element: elementRef) {

   }

   ngDoCheck() {
     this.style = { //scope variable style, shared with our controller
         height:this.element.nativeElement.offsetHeight+'px', //set the height in style to our elements height
         width:this.element.nativeElement.offsetWidth+'px' //same with width
     };
   }
}

html

<span HeightSetter [ngStyle]="style"></span>

【讨论】:

  • 得到它的工作,改变
猜你喜欢
  • 2017-09-24
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2013-09-11
  • 2014-11-29
  • 1970-01-01
  • 2015-05-19
  • 1970-01-01
相关资源
最近更新 更多