我正在探索Angular2(Ionic2)中的ElementRef
对象,而我无法控制padding
的{{1}} CSS属性。
对于以下问题,我不会详细说明我的文件:[我的项目] \ src \ app \ app.component.ts和[my project] \ src \ app \ app.module.ts。请假设这些工作正常。
我在[my project] \ src \ pages \ my-component \ my-component.ts下的组件中有这段代码:
ElementRef
然后在[我的项目] \ src \ pages \ my-component \ my-component.html中的这个html模板,我有:
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);
}
}
当我查看<ion-header>
...
</ion-header>
<ion-content >
<ion-card #ionCard>
<ion-card-content #ionCardContent>
</ion-card-content >
</ion-card>
</ion-content>
和console.log
的日志(由ionWillEnter()
中的#ionCard
给出)时:#ionCardContent
碰巧有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属性?
答案 0 :(得分:3)
(感谢GünterZöchbauer的这一次)。
解决方案是:[window object].getComputedStyle(ionCardContent.nativeElement,null).paddingLeft;
它为填充留下了px后缀。
有关this thread中getComputedStyle()
功能的更多输入。