Dawit
Dawit

Reputation: 642

Angular Directive input is not being set

I just cant find this issue here...

The directive:

@Directive({
  selector: '[appListData]'
})
export class ListDataDirective implements OnInit {

  @Input('data') data: object;
  @Input('layout') layout: string;

  templateUrl: string;

  constructor(private el: ElementRef) { }

  ngOnInit(): void {

    console.log(JSON.stringify(this.data));
    console.log(this.layout);

    this.templateUrl = 'list-data-layouts/list.html';

    if (this.layout === 'grid') {
      this.templateUrl = 'list-data-layouts/grid.html';
    } else if (this.layout === 'list') {
      this.templateUrl = 'list-data-layouts/list.html';
    }

  }
}

The template

<div appListData [data]=employees [layout]="grid"></div>

The log outputs : the layout is undefined - WHY?

enter image description here

I am also not sure how to load the external template files in my div. thanks.

EDIT

Per suggestions, doing the following prints out both inputs, I will stick with the second one moving forward. @nkuma_12 answer explains how it's looking for the grid property in the component's class which made sense - as eventually there will be a button changing a layout variable.

<div appListData [data]=employees layout="grid"></div> 
<div appListData [data]=employees [layout]="'grid'"></div>

I have been reading the documentation here on structural directives - nothing helped me out there. https://angular.io/guide/structural-directives#write-a-structural-directive

Upvotes: 0

Views: 2606

Answers (1)

nircraft
nircraft

Reputation: 8478

Since you are using

  @Input('layout') layout: string;

in directives.

When passing input , i see you are passing [layout]="grid"></div> which makes it look for grid variable in your component where it's used and gets undefined.

You should pass value grid in single quotes: [layout]="'grid'"></div>

Also your data input value should be in double quotes: [data]="employees". Please check documentation for more details.

Upvotes: 2

Related Questions