[英]Angular2 attribute directive property
我試圖做一個angular2(4)指令。 我用它來設置div的樣式,並添加背景圖像。 組件使用該指令傳遞背景圖像的源。
我無法訪問輸入。 它一直返回undefined
繼承人我所做的
image-style
指令
import { Directive, ElementRef, Input } from '@angular/core';
@Directive({
selector: '[image-style]' // Attribute selector
})
export class ImageStyleDirective {
@Input("image-style") imageSrc: string;
constructor(public el: ElementRef) {
console.log('Hello ImageStyleDirective Directive');
console.log(this.imageSrc); //THIS RETURNS UNDEFINED EVERY TIME
this._setProperties();
}
_setProperties(){
console.log(this.imageSrc);
this.el.nativeElement.style.width = "70px";
this.el.nativeElement.style.height = "70px";
this.el.nativeElement.style.borderRadius = "50%";
this.el.nativeElement.style.backgroundSize = "contain";
this.el.nativeElement.style.backgroundPosition = "center center";
this.el.nativeElement.style.backgroundRepeat = "no-repeat";
this.el.nativeElement.style.backgroundColor = "#2d2439";
this.el.nativeElement.style.backgroundImage = "url('"+this.imageSrc+"')";
}
comonent.html
使用指令
<div class="item-block">
<ion-grid>
<ion-row align-items-center>
<ion-col class="image">
<div [image-style]="brand.image"></div>
</ion-col>
<ion-col col-9>
<div class="name">{{brand.name}}</div>
<div class="category">{{brand.category}}</div>
<div class="location">{{brand.location}}</div>
</ion-col>
</ion-row>
</ion-grid>
</div>
這是我第一次嘗試這樣的事情。 我明確遵循了文檔 ,但仍然無法訪問該屬性。 我不確定我在哪里錯過任何建議?
根據上面的@jonrsharpe(在注釋中)在構造函數中無法訪問輸入。 因此,我將其移至了ngOnInit()
生命周期掛鈎,並成功了!
import { Directive, ElementRef, Input } from '@angular/core';
@Directive({
selector: '[image-style]' // Attribute selector
})
export class ImageStyleDirective {
@Input("image-style") imageSrc;
constructor(public el: ElementRef) {
console.log('Hello ImageStyleDirective Directive');
}
ngOnInit(){
console.log(this.imageSrc);
this._setProperties();
}
_setProperties(){
console.log(this.imageSrc);
this.el.nativeElement.style.width = "70px";
this.el.nativeElement.style.height = "70px";
this.el.nativeElement.style.borderRadius = "50%";
// max-width: 40%;
// this.el.nativeElement.style.margin = "auto";
this.el.nativeElement.style.backgroundSize = "contain";
this.el.nativeElement.style.backgroundPosition = "center center";
this.el.nativeElement.style.backgroundRepeat = "no-repeat";
this.el.nativeElement.style.backgroundColor = "#2d2439";
this.el.nativeElement.style.backgroundImage = "url('"+this.imageSrc+"')";
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.