Skip to content

amitport/ngx-init

Repository files navigation

NgxInit

Angular.js' ng-init directive for Angular.

This project was generated with Angular CLI version 8.3.18.

usage

The usage involves some boilerplate, but that's the best Angular currently has to offer

  1. import NgxInitModule
  2. a value expression is set via [ngxInit] on an ng-template and published into a variable name via let-<you-var-name>=ngxInit

Examples

simple

the following are equivalent (assuming i and j are defined in the context):

<div *ngxInit="3 * i + j as idx">{{idx}}</div>
<ng-container *nxgInit="3 * i + j as idx">
  <dt>{{idx}}</dt>
  <dd>this is the {{idx}} index</dd>
</ng-container>
<ng-template [ngxInit]="3 * i + j" let-idx="ngxInit">
  <dt>{{idx}}</dt>
  <dd>this is the {{idx}} index</dd>
</ng-template>

inside ngFor

In the simple case, this directive cannot be used inside ngFor because in angular we can't have multiple template bindings on one element. In order to bypass this limitation we can use either ng-container or ng-template

<!-- Error: can't have multiple template bindings on one element -->
<div *ngFor="let i of [0, 1, 2]" *nxgInit="i * i as sqr" (click)="onClick(sqr)">
  {{sqr}}
</div>

Workarounds:

<ng-container *ngFor="let i of [0, 1, 2]">
  <div *ngxInit="i * i as sqr" (click)="onClick(sqr)">{{sqr}}</div>
</ng-container>
<ng-template ngFor let-i [ngForOf]="[0, 1, 2]">
  <div *ngxInit="i * i as sqr" (click)="onClick(sqr)">{{sqr}}</div>
</ng-template>

with async pipe

<ng-container *ngxInit="(state$ | async) as state">
  <table id="board">
    <tr *ngFor="let i of [0, 1, 2]">
      <ng-container *ngFor="let j of [0, 1, 2]">
          <td *ngxInit="3 * i + j as id" [ngClass]="{active: isActive(state, id)}" (click)="clickCell(id)">{{state.G.cells[id]}}</td>
      </ng-container>
    </tr>
  </table>
</ng-container>

About

Angular.js' ng-init directive for Angular2+

Topics

Resources

License

Stars

Watchers

Forks

Releases

No releases published

Packages

No packages published