Skip to content

Flow type information across *ngFor-like directives #12398

Closed

Description

@chuckjaz

This issues supersedes and replaces the proposals in #10510 and #4850.

The problem

Assume the following code example:

@Component({
  template: `
  <ul>
    <li *ngFor="let person of people; let i = index">{{i + 0}}: {{person.last}}, {{person.first}}<li>
  <ul>
`
})
class MyExample {
  people: Person[] = [];
}

class Person {
  first: string;
  last: string;
}

In Angular 2.1, the generated code for person.first is not type checked because the type of person is generated as any. The type of person should be Person. This would also allow the Angular language service to supply first and last as completions for the expression person. in the interpolations.

Solution

  1. Change type of NgFor and NgForRow to take a type parameter T.
  2. Change type of ngForOf to be T[] | Iterable<T>.
  3. Change $implicit in NgForRow to be of type T.
  4. Modify the code generation to flow the type from the input bindings to the type parameters.

The modified NgFor and NgForRow would look like:

export class NgForRow<T> {
  constructor(public $implicit: T, public index: number, public count: number) {}
  ...
}

@Directive({selector: '[ngFor][ngForOf]'})
export class NgFor<T> implements DoCheck, OnChanges {
  @Input() ngForOf: T[] ;
  @Input() ngForTrackBy: TrackByFn;

  private _differ: IterableDiffer = null;

  constructor(
      private _viewContainer: ViewContainerRef, private _template: TemplateRef<NgForRow<T>>,
      private _differs: IterableDiffers, private _cdr: ChangeDetectorRef) {}

  @Input()
  set ngForTemplate(value: TemplateRef<NgForRow<T>>) {
    if (value) {
      this._template = value;
    }
  }

 ...
}

Here is now a similar example from the above could be generated that flows the types from the input properties to the type parameters:

// User Provided types
class Person {
    first: string;
    last:string;
}

class MyComp {
    items: string[];
    people: Person[];
}


// Types representing relavant parts of the corresponding types in Angular
class AppView<T> {
    context: T;
}

interface TemplateRef<T> { create(context: T): ViewRef<T>; contextType: T }
interface ViewRef<T> { context: T }


class NgForRow<T> {
    $implicit: T;
    index: number;
}

class NgFor<T>{
    of: T[];
    constructor(template: TemplateRef<NgForRow<T>>) { }
}

/**
 * Assume we have template such as this:
 * <div *ngFor="let person of people; let index = index">
 *   {{index}}: {{person.first}}
 * </div>
 */

// We can auto generate the following function which captures the
// type relation between `of` property and `template`.

function NgFor_Template<T>(of: T[]): TemplateRef<NgForRow<T>> { return undefined as any; }
function NgFor_T<T>(of: T[]): T { return undefined as any; }

// These global variables are here only to flow the type information.
var _comp: MyComp;

// The template row can be constructed as:
var template = NgFor_Template(_comp && _comp.people);
var row: typeof template.contextType;

class RowView extends AppView<typeof row> {
}
var rowView = new RowView();

// Note the type of person is People
var person = rowView.context.$implicit;

// The correct NgFor can be constructed as:
var p1 = NgFor_T(_comp && _comp.people);
var ngFor = new NgFor<typeof p1>(template);

Try it in the TypeScript playground.

Activity

  1. added
    area: core
    feature
    on Oct 19, 2016
  2. 15 remaining items

  3. seangwright commented on Oct 25, 2017

    @seangwright

    @chuckjaz I'm wondering what is the current status of this feature?

    I'm using the following versions

    Angular CLI: 1.5.0-rc.3                                     
    Node: 8.6.0                                                 
    OS: win32 x64                                               
    Angular: 5.0.0-rc.5                                         
    ... animations, common, compiler, compiler-cli, core, forms 
    ... http, language-service, platform-browser                
    ... platform-browser-dynamic, router                        
                                                                
    @angular/cdk: 2.0.0-beta.12                                 
    @angular/cli: 1.5.0-rc.3                                    
    @angular/material: 2.0.0-beta.12                            
    @angular-devkit/build-optimizer: 0.0.31                     
    @angular-devkit/core: 0.0.20                                
    @angular-devkit/schematics: 0.0.34                          
    @ngtools/json-schema: 1.1.0                                 
    @ngtools/webpack: 1.8.0-rc.3                                
    @schematics/angular: 0.0.48                                 
    typescript: 2.5.3                                           
    webpack: 3.8.1                                              
    

    In my template I'm using async and a template variable but I lose typing support with the template variable.

    <ng-container *ngIf="(notes | async) as notesData; else emptyList">
      <mat-list-item *ngFor="let note of notesData">
        <div class="date">
          <div class="month-day">{{note.dateCreated | date: 'MM/dd'}}</div>
        </div>
      </mat-list-item>
    </ng-container>
    
    <ng-template #emptyList>
      <mat-list-item>
        <div *ngIf="!isLoading" class="content">No notes were found</div>
      </mat-list-item>
    </ng-template>
    

    Here notesData has type any and therefore note has type any. If I rename notesData to notes, the compiler is ok but I then lose typing support on (notes | async).

    It would be great to leverage all this great template syntax but if the typing support isn't there I'm more likely to not use the async pipe and instead manage my subscriptions within my component.

    My alternative (to keep the template typing support) is to use the async pipe twice and then use .publishLast().refCount() on the observable in my component class.

    this.isLoading = true;
    
    this.notes = this.dashboardService
      .getRecentNotes()
      .catch(_failure => Observable.of([]))
      .do(() => (this.isLoading = false))
      .publishLast()
      .refCount();
    
    <ng-container *ngIf="(notes | async).length > 0 else emptyList">
      <mat-list-item *ngFor="let note of (notes | async)">
        <div class="date">
          <div class="month-day">{{ note.dateCreated | date: 'MM/dd'}}</div>
    ...
    
  4. added this to the Backlog milestone on Jan 23, 2018
  5. mmatthews06 commented on Jul 14, 2019

    @mmatthews06

    Has there been any movement on this? I understand the benefits of TypeScript, are they really being tossed out the window in half the framework's code? Is there a sort of workaround for this?

  6. simeyla commented on Aug 10, 2019

    @simeyla

    @mmatthews06 Looks like this is a similar issue - which I about understand 50%!

    PS. I'm trying to do this with [ngTemplateOutletContext] where I seem to [need a function to coerce the type] :-((https://stackoverflow.com/questions/55458421/ng-template-typed-variable/57438839#57438839).

  7. pauldraper commented on Aug 23, 2019

    @pauldraper
    Contributor

    @mmatthews06 workaround is to either migrate to React or other JSX-based system (which has had excellent TS support for years), or to migrate to Angular Ivy, which looks at the types of special static properties.

  8. amitport commented on Oct 31, 2019

    @amitport
    Contributor

    @pauldraper Angular Ivy still suffers from the same issue

  9. shackijj commented on Jan 28, 2020

    @shackijj

    I tested Angular Ivy yesterday. The problem is solved for ngFor and ngForOf.

    package.json

    {
      ...
      "dependencies": {
        "@angular/animations": "~8.2.14",
        "@angular/common": "~8.2.14",
        "@angular/compiler": "~8.2.14",
        "@angular/core": "~8.2.14",
        "@angular/forms": "~8.2.14",
        "@angular/platform-browser": "~8.2.14",
        "@angular/platform-browser-dynamic": "~8.2.14",
        "@angular/router": "~8.2.14",
        "rxjs": "~6.4.0",
        "semantic-ui-css": "^2.4.1",
        "tslib": "^1.10.0",
        "zone.js": "~0.9.1"
      },
      "devDependencies": {
        "@angular-devkit/build-angular": "~0.803.23",
        "@angular/cli": "~8.3.23",
        "@angular/compiler-cli": "~8.2.14",
        "@angular/language-service": "~8.2.14",
        "@types/node": "~8.9.4",
        "@types/jasmine": "~3.3.8",
        "@types/jasminewd2": "~2.0.3",
        "codelyzer": "^5.0.0",
        "jasmine-core": "~3.4.0",
        "jasmine-spec-reporter": "~4.2.1",
        "karma": "~4.1.0",
        "karma-chrome-launcher": "~2.2.0",
        "karma-coverage-istanbul-reporter": "~2.0.1",
        "karma-jasmine": "~2.0.1",
        "karma-jasmine-html-reporter": "^1.4.0",
        "protractor": "~5.4.0",
        "ts-node": "~7.0.0",
        "tslint": "~5.15.0",
        "typescript": "~3.5.3"
      }
    }
    
  10. JoostK commented on Mar 14, 2020

    @JoostK
    Member

    Support for strict checking of ngFor is fully working using Ivy, if strictTemplates (with at least strictInputTypes) is enabled.

  11. angular-automatic-lock-bot commented on Apr 14, 2020

    @angular-automatic-lock-bot

    This issue has been automatically locked due to inactivity.
    Please file a new issue if you are encountering a similar or related problem.

    Read more about our automatic conversation locking policy.

    This action has been performed automatically by a bot.

  12. locked and limited conversation to collaborators on Apr 14, 2020
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Metadata

Metadata

Assignees

Labels

area: corebreaking changeseffort2: daysfeaturefreq3: high

Type

No type

Projects

No projects

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions