【问题标题】:angular2: ElementRef get CSS padding attributeangular2: ElementRef 获取 CSS 填充属性
【发布时间】:2017-04-24 22:29:48
【问题描述】:

我正在探索 Angular2 (Ionic2) 中的 ElementRef 对象,但我无法控制 ElementRefpadding CSS 属性。

对于以下问题,我不会提供我的文件的详细信息:[my project]\src\app\app.component.ts 和 [my project]\src\app\app.module.ts。请假设这些工作正常。

我在 [我的项目]\src\pages\my-component\my-component.ts 下的组件中有此代码:

import { Component,  ContentChild, ViewChild, ElementRef } from '@angular/core';
import { NavController, Card, CardContent } from 'ionic-angular';

@Component({
    selector:'my-component',
    templateUrl: 'my-component.html'
})
export class MyComponentPage {
    // @ContentChild("ionCard") ionCard:Card;
    // @ContentChild("ionCardContent") ionCardContent:CardContent;
    @ViewChild("ionCard") ionCard:ElementRef;
    @ViewChild("ionCardContent") ionCardContent:ElementRef;
    constructor(public navCtrl:NavController){

    }
    ionViewWillEnter(){
        console.log("ionCard: ", ionCard);
        console.log("ionCardContent: ", ionCardContent);

    }
}

然后这个html模板在[我的项目]\src\pages\my-component\my-component.html,我有:

<ion-header>
...
</ion-header>
<ion-content >
  <ion-card #ionCard>
    <ion-card-content #ionCardContent>
    </ion-card-content >
  </ion-card>
</ion-content>

当我查看#ionCard#ionCardContent 的日志(由ionWillEnter() 中的console.log 给出)时:它们恰好具有ElementRef.nativeElement.clientWidth 相同的值。这可能很好,但我可以在我的 Chrome 检查控制台(通过样式选项卡)中看到#IonCardContent 有一个padding。而&lt;ion-card-content&gt; 中真正的可用空间宽度是:(ElementRef.nativeElement.clientWidth - padding)。而且我在ElementRef.nativeElement 属性中找不到此填充的位置。

当我查看ElementRef.nativeElement.style 时,所有属性都有一个空字符串值(其中paddingLeft)。

我也尝试过ContentChild(您可以看到这些行在我的代码中被注释,并且相应的导入位于文件顶部)。由于&lt;ion-card&gt;&lt;ion-card-content&gt; 不是标准的DOM 语法,我想值得一试。但在这种情况下,我在日志中得到一个undefined

有人知道如何在 Angular2 中达到 ElementRef.nativeElement 的 padding 属性吗?

【问题讨论】:

  • @Günter Zöchbauer 好的,你带我找到一个解决方案:[window object].getComputedStyle(ionCardContent.nativeElement,null).paddingLeft);给我左边的填充(带有 px 后缀)。你想把它写成答案吗?

标签: css angular ionic2


【解决方案1】:

(感谢 Günter Zöchbauer 的这篇文章)。

解决办法是:[window object].getComputedStyle(ionCardContent.nativeElement,null).‌​paddingLeft;

它给出了带有 px 后缀的填充。

关于this thread 中的getComputedStyle() 函数的更多输入。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-11-10
    • 2010-12-20
    • 2021-11-27
    • 2014-07-17
    • 2013-01-18
    • 2015-11-05
    相关资源
    最近更新 更多