1
私はangular2(4)ディレクティブを作成しようとしています。私は、divのスタイルを設定し、背景画像を追加するために使用します。背景イメージのソースは、そのディレクティブを使用するコンポーネントによって渡されます。Angular2属性ディレクティブのプロパティ
入力にアクセスできません。それは私が指示
<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>
これが私の最初の時間は、このような何かをしようとしているを使用して
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
をやったundefined
相続人を返し続けます。私はdocumentationを明示的にフォローしていますが、私はまだそのプロパティにアクセスできません。私はそれを逃したかわからない 何か提案がありますか?
コンストラクタでは定義されていないため、入力はライフサイクルの後半までアクセスできません。 – jonrsharpe
ディレクティブをdivに適用する必要があります。 – Cristophs0n
@jonrsharpeそれは働いた!ありがとう。 'ngOnInit()'ライフサイクルフックで 'this._setProperties()'を作った –