【发布时间】:2017-04-24 22:29:48
【问题描述】:
我正在探索 Angular2 (Ionic2) 中的 ElementRef 对象,但我无法控制 ElementRef 的 padding 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。而<ion-card-content> 中真正的可用空间宽度是:(ElementRef.nativeElement.clientWidth - padding)。而且我在ElementRef.nativeElement 属性中找不到此填充的位置。
当我查看ElementRef.nativeElement.style 时,所有属性都有一个空字符串值(其中paddingLeft)。
我也尝试过ContentChild(您可以看到这些行在我的代码中被注释,并且相应的导入位于文件顶部)。由于<ion-card> 和<ion-card-content> 不是标准的DOM 语法,我想值得一试。但在这种情况下,我在日志中得到一个undefined。
有人知道如何在 Angular2 中达到 ElementRef.nativeElement 的 padding 属性吗?
【问题讨论】:
-
@Günter Zöchbauer 好的,你带我找到一个解决方案:[window object].getComputedStyle(ionCardContent.nativeElement,null).paddingLeft);给我左边的填充(带有 px 后缀)。你想把它写成答案吗?