makkasi
makkasi

Reputation: 7298

How to expose directive property to be used inside directive content

https://plnkr.co/edit/6Rf11kBMpXH09tbksj1J?p=preview

app.component.ts:

    @Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  list$: Observable<any>;

  constructor () {
    let list = [
    {color : 'red', op: 70},
    {color : 'green', op: 80},
    {color : 'blue', op: 60},
    {color : 'yellow', op: 50},
    {color : 'black', op: 40}
    ];
    this.list$ = Observable.from(list);
  }
}

app.component.html

<div direc [data]="list$">
     List fetched data
      <ul>
        <li *ngFor="let item of items">{{item.color}}</li>
      </ul>
  </div>

The directive code is:

    import { Input, Directive, AfterViewInit } from '@angular/core';
@Directive({
  selector: '[direc]'
})
export class DirecDirective implements AfterViewInit {
  @Input()
  data;

  items: any[];

  constructor() {}
  ngAfterViewInit() {
    this.data.take(3).toArray().subscribe(data => this.items = data);
    console.log(this.items);
  }

}

I cannot access the items list in the <li></li>. How to access the decorator property items?

What I've done is to pass Observable to the directive. In ngAfterViewInit method I have the Observable and I use it to get the data. The data is assigned to directive item property and I try to use it inside the directive content. There are not errors in the browser console and the items are listed successfully in the ngAfterViewInit method. In the plunker is more simplified: https://plnkr.co/edit/6Rf11kBMpXH09tbksj1J?p=preview

The *ngFor is directive inside the direc directive. Should have access to the direc directive items, but it doesn't. Or at least there is nothing rendered.

Upvotes: 2

Views: 1206

Answers (1)

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

Reputation: 657406

The items is not available, because the properties of the directive are not in scope there. What you can do use exportAs

@Directive({ 
  selector: '[direc]', 
  exportAs: 'direc', 
}) export class DirecDirective ... { 

make it available as a template variable

<div #d="direc" direc [data]="list"> 

and then access it using that variable

<li *ngFor="let item of direc.items">{{item.color}}</li>

Plunker example

Upvotes: 3

Related Questions