ngxtension/ngxtension-platform

feat: repeat pipe for new @for syntax

Dafnik opened this issue · 3 comments

The current implementation of the Repeat Directive has limited usage for the new template syntax for loop. (also it's build on inheritenance instead of composition)

My proposal to circumvent these issues would be a RepeatPipe.
It could look something like this:

@Pipe({
  standalone: true,
  name: 'repeat',
})
export class RepeatPipe implements PipeTransform {
  transform(length: number, startAt = 0): number[] {
    if (Number.isNaN(length) || !Number.isInteger(length) || length < 1) {
      throw new Error(
        `[Repeat] repeat requires an positive integer but ${length} is passed in`
      );
    }
    return Array.from({ length }, (_, index) => index + startAt);
  }
}

where the usage is something like this:

@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RepeatPipe],
  template: `
    @for (i of 10 | repeat; track i) {
      <p>Nr. {{i}}</p>
    }

    <hr/>

    @for (i of 10 | repeat: 10; track i) {
      <p>Nr. {{i}}</p>
    }
  `,
})
export class App { }

will result in:
image

That's a good idea.

Great! I looked into the possibility of providing a migration from the current repeat directive to this new repeat pipe but after looking into how Angular does the new control flow syntax migration I'm not sure about that anymore.

The migration can't be done with a simple regex as it would need to actually check if NgFor (or the CommonModule) is already available for the component while doing the migration.

Do you think we can get away with not providing an automatic migration for this (as it's not easily feasible)?

Migration will not be necessary if the old solution will not be removed. The library can provide two approaches (*ngFor and @for)