Angular2属性指令属性

时间:2017-11-05 16:35:42

标签: javascript angular ionic3

我正在尝试制作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>

这是我第一次尝试这样的事情。我明确地跟踪documentation,但我仍然无法访问该物业。我不确定我错过了哪里 有什么建议吗?

1 个答案:

答案 0 :(得分:0)

根据上面的@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+"')";
    }

}
相关问题