How to call a function in <ng-template> let variable declaration Angular 4

Viewed 9183

I have a function which return color,text color and date value from a typescript function as object. which i want to store in a let variable. i can directly use the function but don't want to replicate the calling of function.

This Gives me error like 'year' not found

<kendo-grid-column-group title="{{year}}" [headerStyle]="{'text-align': 'center'}" width="380">
        <ul *ngFor="let month of keys(); let i = index">
          <li>
            <kendo-grid-column field="{{month}}" class="no-padding" title="{{month}}" [filterable]="false" [sortable]="false" width="35">
              <ng-template kendoGridCellTemplate let-dataItem let-color="getColor(year,i,dataItem.ca)">
                <span class="whole-cell" [ngStyle]="{'background-color': color.color,'color': color.textColor,'font-weight':'bold','height':'25px','vertical-align': 'middle'}">
                  <label>{{color.Date}}</label>
                </span>
              </ng-template>
            </kendo-grid-column>
          </li>
        </ul>
</kendo-grid-column-group>
2 Answers

You need to pass 'content:this' scope object.

Template:

<ng-template let-color="getColor()" #loading>
                <span class="whole-cell" [ngStyle]="{'background-color': color.color,'color': color.textColor,'font-weight':'bold','height':'25px','vertical-align': 'middle'}">
                  <label>{{color.Date}}</label>
                </span>
              </ng-template>

<ng-container *ngTemplateOutlet="loading;context:this"></ng-container>

Component:

getColor() {
    return {
      color: 'red',
      textColor: 'blue',
      Date: 'hi'
    }
  }

one technique that can be used is misusing? *ngIf (check version of angular that supports it though)

<ng-container *ngIf="{color:getColor(year,i,dataItem.ca)}; let state">
     {{state.color.Date}}
</ng-container>
  • *ngIf allows to store result of expression in variable.
  • since an object is created, *ngIf will always be thruthy, thus render ng-container
  • ng-container is not rendered as dom element , only its contents
Related