Accessing the length of QueryList inside an Angular2 template

Issue

I have an Angular template that gets children passed to it using:

@ContentChildren(Item) QueryList<Item> items;

Inside the template, these items are placed in a table, firstly used in the table head to display headers:

        <table class="table nomargin table-hover">
            <thead>
            <tr>
                <th *ngFor="let item of items" ngClass="{{item.classes}}">

… which works as expected. While the content is loading, I have a loading gif that spans all the columns displaying a loading gif, I want this loading gif to span the number of columns specified in items

This is what I’ve tried so far:

            <tbody>
            <tr *ngIf="display.loading">
                <td class="text-center ajax-loader" [attr.colspan]="{{items?.toArray().length}}" >
                    <br />
                    <img src="../img/ajax-loader-4.gif"/>
                    <br />
                    <br />
                    Loading ...
                    <br />
                    <br />
                </td>
            </tr>

and it’s failing with:

An error occurred loading file:
package:______/components/table-component.ngfactory.dart

As soon as I remove [attr.colspan]="{{items?.toArray().length}}", the error goes away again. Same error for [attr.colspan]="{{items?.length}}".

items does have a length property so toArray is probably not needed.

In the pub output I’m seeing:

[web] GET
packages/______/components/table-component.ngfactory.dart →
Could not find asset
______|lib/components/table-component.ngfactory.dart.

If I just do colspan="{{items?.length}}" it just gets ignored.

Am I missing some directive? This is what I currently have:

@View(
    directives: const [NgFor, NgIf, NgClass],

What is the right way to make use of the length of items in an attribute in an angular2 template?

Solution

@View()

@View() annotation was removed in beta.11 already. https://github.com/angular/angular/blob/master/CHANGELOG.md#200-beta11-2016-03-18

Just move the parameters to @Component(...) instead.

PLATFORM_DIRECTIVES

If you add

  transformers:
  - angular2/transform/codegen:
      platform_directives: 'package:angular2/src/common/directives.dart#CORE_DIRECTIVES'

to your pubspec.yaml then you don’t need to add these directives explicitely

@View(
    directives: const [NgFor, NgIf, NgClass],`

[] and {{}}

[attr.colspan]="{{items?.length}}"
[] is for object binding, {{}} is for string binding. Both together is invalid.

Supported is either

[attr.colspan]="items?.length"

or

attr.colspan="{{items?.length}}"

while the 2nd assigns the result of items?.length.toString()

Answered By – Günter Zöchbauer

Answer Checked By – Timothy Miller (FlutterFixes Admin)

Leave a Reply

Your email address will not be published.