Я пытаюсь сделать угловую (4) директиву. я использую его для стилей div и добавляю фоновое изображение. источник фонового изображения передается компонентом с использованием этой директивы.
Я не могу получить доступ к вводу. он продолжает возвращать undefined
Heres, что я сделал
директива 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()
жизненного цикла 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+"')";
}
}