Angular directive for holderjs - expression evaluation not working as intended
Asked Answered
C

1

1

I am trying to use the excellent holderjs library in an angular2 project. Someone wrote up a very simple attribute directive which I am trying to use.

holderjs is basically a client side image placeholder generator.

I am trying to modify the directive so that I can pass dynamic placeholders.

For example, this works:

<img holderjs data-src="holder.js/200x200/auto">

But these don't:

<img holderjs data-src="{{myvariable}}"> 
<img holderjs [data-src]="myvariable">

The angular directive is really a simple wrapper that runs Holderjs inside it. I've tried moving the code to ngOnInit as well as tried to specify data-src as an @Input but haven't had success so far.

Any ideas? I've set up a plunker to demonstrate the issue: https://plnkr.co/edit/ibOyJvmNWadQWOm6Ki7u?p=info

The code is in home.page.ts & html

The core problem is holderjs inserts a src img tag based on the URL provided in data-src but when using either expression evaluation or binding (adding an @Input to the directive), the src tag doesn't get created.

Catmint answered 10/10, 2017 at 17:29 Comment(0)
W
3

You should know two things about your problem:

  • Anguler is stripping the data- prefix in the compiler (the idea behind this was that people could prefix non-standard attributes with bindings) so you have to use attribute binding looking something like:

    attr.data-src="{{myvariable}}"or [attr.data-src]="myvariable"

  • Attribute binding won't be appeared until ngAfterViewInit is called therefore you should fire your plugin inside ngAfterViewInit hook:

holderjs.directive.ts

@Directive({
  selector: '[holderjs]',
})
export class HolderjsDirective {
  constructor(public el: ElementRef) {}

  ngAfterViewInit() {
     Holder.run({images:this.el.nativeElement});
  }
}

Plunker Example

Whity answered 10/10, 2017 at 18:1 Comment(1)
YOU. ARE. THE. MAN ! thank you. Been at this since yesterday!Catmint

© 2022 - 2024 — McMap. All rights reserved.