Angular directive for holderjs - expression evaluation not working as intended

百般思念 提交于 2020-05-16 04:40:48

问题


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.


回答1:


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



来源:https://stackoverflow.com/questions/46672595/angular-directive-for-holderjs-expression-evaluation-not-working-as-intended

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!