Jokin
Jokin

Reputation: 4218

capture property binding in angular

I want to capture the [src] property binding to modify it with a directive and prepend with a url prefix.

<img class="logo" tv-user-content [src]="config.logo" *ngIf="config !== undefined"/>

and this directive

import { AfterContentInit, AfterViewInit, Directive, ElementRef, Input, Renderer } from '@angular/core';

@Directive({
  selector: '[tv-user-content]'
})
export class UserContentDirective implements AfterContentInit {

  @Input() src: string;

  constructor(
    private el: ElementRef
  ) {
  }

  ngAfterContentInit() {
    this.el.nativeElement.setAttribute('src',"myprefix" + this.src);
  }
}

is this posible?

Upvotes: 1

Views: 56

Answers (1)

G&#252;nter Z&#246;chbauer
G&#252;nter Z&#246;chbauer

Reputation: 657018

You can make src an input with a setter and add the prefix if it wasn't added yet, to prevent an endless loop:

export class UserContentDirective implements AfterContentInit {

  @Input() set src(value: string) {
    if(!value) {
      this.prefixedSrc = null;
    } else {
      if(value.startsWith("myprefix") {
        this.prefixedSrc = value;
      } else {
        this.prefixedSrc = `myprefix${value}`;
      }
    }
  }

  @HostBinding('src') 
  prefixedSrc:string;
}

Upvotes: 1

Related Questions