asdf_enel_hak asdf_enel_hak - 6 months ago 21
AngularJS Question

How to set initial value in directive property

In this plunker:
I have a attribute directive called

myTrimmer
that trims long text:

which works fine for static text

<div myTrimmer="10">some longgggg texttttttttttttttt</div>


but does not work for interpolated one:

<div myTrimmer="10">{{myText}}</div>


that means it takes empty string instead of
myText
at line

this.originalValue = this.el.nativeElement.innerHTML;


Here it is set property of directive:

set myTrimmer(value: string) {
this.originalValue = this.el.nativeElement.innerHTML;
this.length = +value;
if (+value < this.el.nativeElement.innerHTML.length)
this.el.nativeElement.innerHTML = this.el.nativeElement.innerHTML.substring(0, value) + '...';
}

Answer

I suppose that this way you need to wait AfterViewInit event like this:

export class MyTrimmer {
  myTrimmer: string;
  ngAfterViewInit() {
    this.originalValue = this.el.nativeElement.innerHTML;
    console.log(this.originalValue);
    this.length = +this.myTrimmer;
    if (+this.myTrimmer < this.el.nativeElement.innerHTML.length)
      this.el.nativeElement.innerHTML = 
this.el.nativeElement.innerHTML.substring(0, this.myTrimmer) + '...';
  }
}

See also at this updated plunkr https://plnkr.co/edit/MccvTyQxSpcgO6Tj99QX?p=preview