Home > Blockchain >  How to define variable in ng-container?
How to define variable in ng-container?

Time:03-03

In another component of my Angular 12 based web application I am already using an ng-container with *ngFor to iterate over an array and display a control for each item in the array like this:

<ng-container *ngFor="let parameter of parameters">
    ....
</ng-container>

Now I need to do almost the same thing, but without iterating over anything. I simply want to have a container with a variable defined which I can then use inside the container. I already tried to use *ngVar instead of *ngFor but then I got this error:

Can't bind to 'ngVar' since it isn't a known property of 'ng-container'.

How can I do the same thing like I already did with the *ngFor but for a single variable and without iterating over anything? I do not want to use a div because I do not want the container element to actually exist in the HTML of my application after it was rendered. I assume that there is a simple solution for this but so far I wasn't able to find it.

Here is how I'd like to use this feature:

<ng-container
  *ngFor="let parameterColumn of parameterColumns"
  matColumnDef="{{ parameterColumn }}"
>
  <th mat-header-cell *matHeaderCellDef>
    {{ parameterColumn }}
  </th>
  <td mat-cell *matCellDef="let element">
    <ng-container variable="parameter = getParameterById(element, parameterColumn)">
      ...
    </ng-container>
  </td>
</ng-container>

CodePudding user response:

Am not sure what exactly you want, but ng-template has the variables functionality you require, you can use it together with ng-container to not insert any additional html, please refer the below pattern, where variables are inserted using context.

Update: OP has provided inputs so code modified so that the variables are hardcoded in the ng-container as follows

In the below example the variables are hard coded and you can insert this anywhere in the component and reuse the hardcoded variables.

<ng-container *ngTemplateOutlet="template; context: { variableToBeUsed: 'variable to be used' }"></ng-container>
<ng-template #template let-test="variableToBeUsed">
  <h1>variable to be used: {{ test }}</h1>
</ng-template>

controller

import { Component } from '@angular/core';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
})
export class AppComponent {
  name = 'Angular 6';
}

stackblitz

  • Related