Search code examples
dartangular-dart

How to set custom model object for each element when using *ngFor in AngularDart


I have an Angular Dart page where I need to create a component on the screen for each item in a collection. The items are custom model objects:

    class CohortDataSourceAssay{
      String name;
      String displayName;
      bool selected;
      List<String> platforms = new List<String>();

      CohortDataSourceAssay();
    }

I have a parent page where I want to create a template for each element in a collection of the class above:

    <data-source-assay *ngFor="let assay of dataSource.assays"></data-source-assay>

Here is the markup for the data-source-assay component:

    <div class="dataSourceAssay">
        <material-checkbox [(ngModel)]="assay.selected" (ngModelChange)="onCbxChange($event)">{{assay.displayName}}</material-checkbox>
        <material-dropdown-select class="selectStyle"
                                  [disabled]="!assay.selected"
                                  [buttonText]="platformLabel"
                                  [selection]="assaySequencingPlatforms"
                                  [options]="sequencingPlatforms"
                                  [itemRenderer]="itemRenderer">
        </material-dropdown-select>
    </div>

This works insofar as it loads a block for each assay element in dataSource.assays, however the assay block does not appear to get the assay model object. It appears to be null. How do I pass it in?


Solution

  • You need to declare an @Input() on your <data-source-assay> component, through which you can pass the assay value.

    @Component(...)
    class DataSourceAssayComponent {
      // An input makes this property bindable in the template via [] 
      // notation.
      //
      // Note: I'm not actually sure what the type of `assay` is in your
      // example, so replace `Assay` with whatever the correct type is.
      @Input()
      Assay assay;
    }
    

    Now in your template where you create this component, you can bind the assay value to the input.

    <data-source-assay
        *ngFor="let assay of dataSource.assays"
        [assay]="assay">
    </data-source-assay>
    

    Remember that the local values in a template are local to that template. Meaning the assay you were declaring in your ngFor isn't visible anywhere outside of that current template.