mteb/FreshStackRetrieval huggingface dataset:
I am having different levels of closure using *ngFor directive and the new @for block.  I have a parent component that creates multiple child components using a for loop:
        <app-active-problem class="panel" *ngFor="let activeProblem of summary.activeProblems" [activeProblem] = "activeProblem" (update)="updateActiveProblem($event);"></app-active-problem>
        <!--
        @for (activeProblem of summary.activeProblems; track $index) {
            <app-active-problem class="panel" [activeProblem] = "activeProblem" (update)="updateActiveProblem($event);"></app-active-problem>
        }-->
      </ng-container>

In the child component I accept the [activeProblem] input as either a ProblemGroup | NarrativeProblem class.  In order to effectively distinguish between the two and render a view.  I create two instance variables
  problemGroup?: ProblemGroup;
  narrativeProblem?: NarrativeProblem;

  ngOnInit(): void {
    if (this.activeProblem instanceof ProblemGroup) {
      this.problemGroup = this.activeProblem as ProblemGroup;
    } else {
      this.narrativeProblem = this.activeProblem;
    }
  }

Within this same view I have a click event handler that toggles the value under the problem group (essentially mutating the object).
            <input
              clrCheckbox
              type="checkbox"
              [checked]="p.value"
              (change)="toggle($event, $index)"
            />

If I have rendered the child component using @for when assigning activeProblem to problemGroup it loses it's reference, effectively creating a copy of the object.  So any mutations I do in the child component is not reflected in the original object.
If I have rendered the child component using *ngFor directive, then it works as expected, any mutations I make to problemGroup effectively points to activeProblem.
I am hoping I can get some clarity on why this is happening?
I'm using Angular 17 with the following code:
database.component.html
@for(user of (users | userPipe:filters); track user.id) {
    <tr id="{{ user.id }}">
        <td>{{ user.name }}</td>
        <td>{{ user.surname }}</td>
        <td>{{ user.age }}</td>
    </tr>
}
@empty {
    <tr>
        <td colspan="3">Empty</td>
    </tr>
}

filters is a string array with the keywords for filtering the matched database entries.
database.pipe.ts
@Pipe({
    name: 'userPipe',
    pure: false
})
export class databasePipe implements PipeTransform {
    transform(values: Users[], filters: string[]): Users[] {
        
        if (!filters || filters.length === 0 || values.length === 0) {
            return values;
        }

        return values.filter((value: User) => {
            filters.forEach(filter => {
                const userNameFound = value.name.toLowerCase().indexOf(filter.toLowerCase()) !== -1;
                const userSurnameFound = value.surname.toLowerCase().indexOf(filter.toLowerCase()) !== -1;
                const ageFound = value.age.toLowerCase().indexOf(filter.toLowerCase()) !== -1;

                if (userNameFound || userSurnameFound || ageFound) {
                
                    console.log("value: ", value);
                    return value;
                }
                return "";
            });
        });
    }
}

It is working and I can see matching entries with value: <value> in the browser console just fine but my filtered table just returns "Empty" and no data is shown.
Does anyone know why this happens?
We are using Angular 17 along with Reactive forms in our project.
We have written a custom directive which formats the output to US phone number format 111-222-3333.
What we are seeing is that when someone tries to copy a number into the field - the field gets formatted, but the validator is still saying it is not valid.
HTML Code:
 <input matInput phoneFormatterDirective placeholder="Enter Phone" formControlName="phone"
                class="inputEntry">

Typescript Code:
phone: new FormControl(null, [Validators.pattern('^[0-9]{3}-[0-9]{3}-[0-9]{4}$')])

Custom Directive Code:
import {Directive, HostListener} from '@angular/core';

@Directive({
  selector: '[phoneFormatterDirective]'
})
export class PhoneFormatterDirective {

  @HostListener('input', ['$event'])
  onKeyDown(event: KeyboardEvent) {
    event.preventDefault();
    const input = event.target as HTMLInputElement;
    console.log(input.value);
    let trimmed = input.value
      .replaceAll('-','')
      .replaceAll('(','')
    .replaceAll(')','')
    .replaceAll(/\s+/g, '');
    if (trimmed.length > 12) {
      trimmed = trimmed.substr(0, 12);
    }
    let numbers = [];
    numbers.push(trimmed.substr(0,3));
    if(trimmed.substr(3,2)!=="")
      numbers.push(trimmed.substr(3,3));
    if(trimmed.substr(6,3)!="")
      numbers.push(trimmed.substr(6,4));

    input.value = numbers.join('-');
    console.log(numbers.join("-"));
  }
}

Let's say I am trying to paste (555) 123-1234 - the value gets formatted to 555-123-1234, but the input says it is still invalid.
It would be valid if I deleted one character and then wrote it manually - which is a kind of strange behavior.
<mat-button-toggle-group appearance="legacy"    [(ngModel)]="selectedClockType">
        <mat-button-toggle *ngFor="let item of items" [value]="item" color="primary">
           {{ item.label }}
        </mat-button-toggle>  
    </mat-button-toggle-group>
       
     @for (item of items; track:item.id) {   
          <ng-container *ngComponentOutlet="item .component"></ng-container> 
        }

     <ng-template #actionItesm let-data="data">{{data}} </ng-template>

component-a.html
    <ng-content></ng-content>

component-b.html
<ng-content></ng-content>

Am Trying to pass ngTemplate by using  below code
 <ng-container *ngComponentOutlet="item .component;content: actionItesm ></ng-container> 

and  using  inside all the components that am using inside Items
I am creating an Angular project and having the following error, which makes my page unable to load:
ERROR NullInjectorError: R3InjectorError(Standalone[_AppComponent])[ActivatedRoute -> ActivatedRoute -> ActivatedRoute]:
NullInjectorError: No provider for ActivatedRoute!
Since it is Angular v17, I do not have AppModule on it.
This is my following code:
app.config.ts
import { ApplicationConfig } from '@angular/core';
import { provideRouter } from '@angular/router';

import { routes } from './app.routes';

export const appConfig: ApplicationConfig = {
  providers: [provideRouter(routes)]
};


app.component.ts
import { Component, LOCALE_ID } from '@angular/core';
import { registerLocaleData } from '@angular/common';
import { RouterLink, RouterLinkActive, RouterOutlet } from '@angular/router';
import { SharedModule } from './shared/shared.module';
import localePT from '@angular/common/locales/pt';

registerLocaleData(localePT);
@Component({
  selector: 'app-root',
  standalone: true,
  imports: [SharedModule, RouterOutlet, RouterLink],
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [{provide: LOCALE_ID, useValue: 'pt-br'}]
})
export class AppComponent {
  title = "app";
}


app.routes.ts
import { Routes } from '@angular/router';
import { HomeComponent } from './features/pages/home/home.component';

export const routes: Routes = [
    { path: 'home', component: HomeComponent },
    { path: '', redirectTo: 'home', pathMatch: 'full' }
];

Thank you in advance!
I tried adding RouterModule.forRoot(routes) in AppComponent, but no success.
I tried to import ActivatedRoute on AppComponent, but it throwed another error: ERROR Error: NG0204: Can't resolve all parameters for ActivatedRoute: (?, ?, ?, ?, ?, ?, ?, ?).
I also tried to import ActivateRoute in AppComponent as the following, but it returns: ERROR Error: NG04002: Cannot match any routes. URL Segment: 'home'
import { Component, LOCALE_ID } from '@angular/core';
import { registerLocaleData } from '@angular/common';
import { ActivatedRoute, RouterLink, RouterOutlet } from '@angular/router';
import { SharedModule } from './shared/shared.module';
import localePT from '@angular/common/locales/pt';
import { routes } from './app.routes';

registerLocaleData(localePT);
@Component({
  selector: 'app-root',
  standalone: true,
  imports: [SharedModule, RouterOutlet, RouterLink],
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css'],
  providers: [{provide: LOCALE_ID, useValue: 'pt-br'}, {provide: ActivatedRoute, useValue: routes}]
})
export class AppComponent {
  title = "app";
}


Since Angular v17 does not have AppModule and does not need it, I did not create it.
I am expecting my page to load properly, it is not allowing it to load.
I'm developing an Angular application and encountering an issue with localStorage in my AuthService. When attempting to use localStorage to store the user's email for authentication purposes, I'm getting an error: "localStorage is not defined".
Here's a simplified version of my AuthService:
//auth.service.ts

import { Injectable } from '@angular/core';
import { Router } from '@angular/router';
import { BehaviorSubject } from 'rxjs';

@Injectable({
    providedIn: 'root',
})
export class AuthService {
    public isAuth = new BehaviorSubject<boolean>(false);

    constructor(private router: Router) {
        this.autoSignIn();
    }

    autoSignIn() {
        if (localStorage.getItem('email')) {
            this.isAuth.next(true);
            this.router.navigate(['/dashboard']);
        }
    }

    signIn(email: string) {
        localStorage.setItem('email', email);
        this.isAuth.next(true);
        this.router.navigate(['/dashboard']);
    }

    signOut() {
        localStorage.removeItem('email');
        this.isAuth.next(false);
        this.router.navigate(['/auth']);
    }
}

I've imported the necessary modules, including Injectable from @angular/core, and I'm using localStorage within my service methods.
I am trying to convert my code directives from Angular 16 to Angular 17. However, I am unable to achieve the reference in Angular 17 so that for both else it will refer to the same ng-template.
<div *ngIf="movies; else noTracks">
    <div *ngIf="movies.length>0; else noTracks">
        <h6 class="m-b-20 m-t-40 p-b-5 b-b-default f-w-600">Favorites</h6>
        <div class="row">
            <div class="col-sm-6">
                <p class="m-b-10 f-w-600">Recent</p>
                <h6 class="text-muted f-w-400">{{movies[movies.length-1].title}}
                    -
                    {{movies[movies.length-1].rating}}</h6>
            </div>
            <div class="col-sm-6">
                <p class="m-b-10 f-w-600">Total</p>
                <h6 class="text-muted f-w-400">{{ movies.length}}</h6>
            </div>
        </div>
    </div>
</div>

<ng-template #noTracks>
    <h6 class="m-b-20 m-t-40 p-b-5 b-b-default f-w-600">Favorites</h6>
    <div class="row">
        <div class="col-sm-6">
            <p class="m-b-10 f-w-600">Recent</p>
            <h6 class="text-muted f-w-400">NA</h6>
        </div>
        <div class="col-sm-6">
            <p class="m-b-10 f-w-600">Total</p>
            <h6 class="text-muted f-w-400">0</h6>
        </div>
    </div>
</ng-template>

In Angular 17 I am trying to achieve the above using @if and @else without using || cause for type never error I will get. Further, I want how we can achieve this.
Note: Don't combine @if statements.
@if (movies) {
  @if (movies.length>0) {
    <h6 class="m-b-20 m-t-40 p-b-5 b-b-default f-w-600">Favorites</h6>
    <div class="row">
      <div class="col-sm-6">
        <p class="m-b-10 f-w-600">Recent</p>
        <h6 class="text-muted f-w-400">{{movies[movies.length-1].title}}
            -
            {{movies[movies.length-1].rating}}</h6>
      </div>
      <div class="col-sm-6">
        <p class="m-b-10 f-w-600">Total</p>
        <h6 class="text-muted f-w-400">{{ movies.length}}</h6>
      </div>
    </div>
  } @else {
    <h6 class="m-b-20 m-t-40 p-b-5 b-b-default f-w-600">Favorites</h6>
    <div class="row">
      <div class="col-sm-6">
        <p class="m-b-10 f-w-600">Recent</p>
        <h6 class="text-muted f-w-400">NA</h6>
      </div>
      <div class="col-sm-6">
        <p class="m-b-10 f-w-600">Total</p>
        <h6 class="text-muted f-w-400">0</h6>
      </div>
    </div>
  }
}
I use angular 17
this is my app.routes.ts
export const routes: Routes = [
  { path: '', pathMatch: 'full', component: HomeComponent },
  { path: 'editors', component: EditorsComponent },
  { path: 'partners', component: PartnersComponent },
  { path: 'investors', component: InvestorsComponent },
  { path: 'telecoms', component: TelecomsComponent },
  { path: 'institutional', component: InstitutionalComponent },
  { path: 'universities', component: UniversitiesComponent },
  { path: 'influencers', component: InfluencersComponent },
  { path: 'ambassador', component: AmbassadorComponent },
];

and my app.config.ts
export function HttpLoaderFactory(http: HttpClient) {
  return new TranslateHttpLoader(http, '/assets/i18n/', '.json');
}

const scrollConfig: InMemoryScrollingOptions = {
  scrollPositionRestoration: 'top',
  anchorScrolling: 'enabled',
};

const inMemoryScrollingFeature: InMemoryScrollingFeature =
  withInMemoryScrolling(scrollConfig);


export const appConfig: ApplicationConfig = {
  providers: [
    provideRouter(routes, inMemoryScrollingFeature),
    provideLottieOptions({
      player: () => import('lottie-web'),
    }),
    provideAnimations(),
    provideHttpClient(),
    TranslateModule.forRoot({
      defaultLanguage: 'en',
      loader: {
        provide: TranslateLoader,
        useFactory: HttpLoaderFactory,
        //useFactory: (http: HttpClient) => new CustomTranslateLoader(http),
        deps: [HttpClient]
      }
    }).providers!, provideClientHydration(), provideClientHydration(), provideClientHydration() ],
};

when I try to go on the page http://localhost/editor i got lot 404 error for example  http://localhost:4200/editors/assets/animations/editor_anim1.json 404
Angular add the name of the page in the path of the ressource. This path should be  http://localhost:4200/assets/animations/editor_anim1.json 404
When I from home then go on page editors and come back on home, the url is http://localhost:4200/editors  and when i go to editor again, now the url is localhost:4200/editors/editors
What's wrong with my routing config ?
The problem basically is that when I'm logged into the dashboard, every time I reload the browser page it renders the login component for an instant
TokenService
export class TokenService {
  isAuthentications: BehaviorSubject<boolean> = new BehaviorSubject<boolean>(false);
  constructor(@Inject(PLATFORM_ID) private platformId: Object) { 
    const token = this.getToken();
    if(token){
      this.updateToken(true)
    }
  }

  setToken(token: string){
    this.updateToken(true);
    localStorage.setItem('user', token)
  }
  updateToken(status: boolean){
    this.isAuthentications.next(status)
  }
  getToken(): string | null{
    if (typeof window !== 'undefined' && window.sessionStorage) {
      return localStorage.getItem('user');
    }

    return null
  }
}

AuthGuard
export const authGuard: CanActivateFn = (route, state) =\> {
const tokenService = inject(TokenService)
const router = inject(Router)
// tokenService.isAuthentications.subscribe({
//   next: (v) =\> {
//     if(!v){
//         router.navigate(['/login'])
//     }
//   }
// })
// return true;

return tokenService.isAuthentications.pipe(map( (user) =\> {
if(!user){
return router.createUrlTree(['/login']);
}else{
return true
}
}))
};

Routes
export const routes: Routes = [
  { path: 'login', component: LoginComponent },
  { path: '', redirectTo: 'login', pathMatch: 'full'},
  {path: '' , component: LayoutComponent, children: [
    {path: 'dashboard', component: DashboardComponent, canActivate: [authGuard]  }
  ]}
];

gif that shows the problem
I've tried other other approaches on how to secure the route however, whenever my guard should redirect to 'login' it has this behavior
I'm encountering an error in my Angular application's template file (dashboard.component.html). The error message is "Object is possibly 'undefined'." Here's the relevant part of the template causing the issue:
<div>
    <p class="title">Dashboard</p>

    <ul>
       @for(post of posts; track post.title){
        @if(post.id%2==0){
            <li>{{post.id}}-{{post.title}}</li>
        }
       }
    </ul>
</div>

// dashboard.component.ts

import { Component } from '@angular/core';
import { AuthService } from '../auth.service';

@Component({
    selector: 'app-dashboard',
    standalone: true,
    imports: [],
    templateUrl: './dashboard.component.html',
    styleUrl: './dashboard.component.scss',
})

export class DashboardComponent {
    email = localStorage.getItem('email');
    posts:any;
    constructor(private authService: AuthService) { 
        this.GetAllPosts();
    }

    signOut() {
        this.authService.signOut();
    }

    GetAllPosts(){
        this.authService.getAllPosts().subscribe((res)=>{
            this.posts = res;
        })
    }
}

The error specifically points to line 10, where I'm trying to iterate over posts using an @for loop and check if post.id % 2 == 0. However, TypeScript is flagging this as a potential error because posts might be undefined or null.
How can I modify this template code to handle the possibility that posts might be undefined while avoiding this error?
In my case ,
I have following block of code,
In which, i can store the info value in the *ngIf expression block and use in the template, how to do the same with newly introduced @if syntax in angular 17 ?
I couldn't find any samples / docs that can do the same using @if syntax.
<div *ngIf="getMatchingImage() as info">
        <img class="empty-cart-img" [src]="info.imageUrl" width="70%" decoding="async" loading="lazy" alt="Empty List">
        <figcaption>
          <ng-content></ng-content>
        </figcaption>
      </div>
Could anyone advise after Angular update up to 18 I got:
An unhandled exception occurred: (0 , os_1.availableParallelism) is not a function
In angular-errors.log
[error] TypeError: (0 , os_1.availableParallelism) is not a function at Object.<anonymous> (C:\Users\Zendbook\Documents\DILAU\tracker-users-web\node_modules\piscina\dist\src\index.js:37:54) at Module._compile (node:internal/modules/cjs/loader:1218:14) at Module._extensions..js (node:internal/modules/cjs/loader:1272:10) at Module.load (node:internal/modules/cjs/loader:1081:32) at Module._load (node:internal/modules/cjs/loader:922:12) at Module.require (node:internal/modules/cjs/loader:1105:19) at require (node:internal/modules/cjs/helpers:103:18) at Object.<anonymous> (C:\Users\Zendbook\Documents\DILAU\tracker-users-web\node_modules\piscina\dist\src\main.js:5:33) at Module._compile (node:internal/modules/cjs/loader:1218:14) at Module._extensions..js (node:internal/modules/cjs/loader:1272:10)
How to fix ?
try to find answer in google.
I have configured klaro cookie package in my Angular project with all the required configurations, but I want to change the icon besides count of service:

I want "+" and "-" icons accordingly when service section is open/close. Is there any way to customize it as per need?
Old icon doesn't fade away:
After upgrading my Angular core libraries to version 18, I migrated to Angular Material 18 by running:
ng update @angular/material
The update went smoothly but when I tried to compile my app I got the following error:
X [ERROR] Undefined function.
   ╷
14 │ $myapp-theme-primary: mat.define-palette(mat.$indigo-palette, A400, A100, A700);
   │                       ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
   ╵
  src\styles.scss 14:23  root stylesheet [plugin angular-sass]

    angular:styles/global:styles:2:8:
      2 │ @import 'src/styles.scss';
        ╵         ~~~~~~~~~~~~~~~~~

My styles.scss worked perfectly with the previous version of Angular Material (v.17). It looks as follows:
@use '@angular/material' as mat;
@include mat.core();

$myapp-theme-primary: mat.define-palette(mat.$indigo-palette, A400, A100, A700);
$myapp-theme-accent: mat.define-palette(mat.$indigo-palette);
$myapp-theme-warn: mat.define-palette(mat.$red-palette);

$myapp-theme: mat.define-light-theme((
  color: (
    primary: $myapp-theme-primary,
    accent: $myapp-theme-accent,
    warn: $myapp-theme-warn,
  )
));

@include mat.all-component-themes($myapp-theme);

How do I have to adapt my code in styles.scss in order to make it work with Angular Material 18?
I want to use the new @for syntax together with @empty to either show the user a table or some text telling there is no data.
With ngFor I usually checked the length of the data array. If not empty:

Add the table header
ngFor the data
Add the table footer

With the newer syntax I hoped to be able to combine those 3 steps above into the @for itself like this:
@for(order of licenseOverview.orders; track order.id; let firstRow = $first; let lastRow = $last) {
   @if(firstRow) {
       <table ...
   }

   <tr>
       <td>{{ order.reference }}</td>
       <td>{{ ... }}</td>
   </tr>

   @if(lastRow) {
       ... </table>
   }
}
@empty { <p>No data for you!</p> }

I expected this to just compile and render the table, but it seems like Angular can't handle this. Is there a way to get this to work?
EDIT: The error I get looks like this:
            @if(firstRow) {
                <table class="table table-responsive ds-table">
                    <thead>
                        <tr>
                            <th>{{ 'Order' }}</th>
                            <th>{{ 'Expected On' }}</th>
                            <th>{{ 'Status' }}</th>
                        </tr>
                    </thead>
                    <tbody>
            } ---> Unexpected closing block
I have tried to use the deploy url with localhost:4100 but this did not change the port of the final builded server.mjs file in the dist folder
I would like to to have a different port than 4000 when i run the server.mjs file on a remote virtual machine
I upgraded to Angular 18 (and adjusted the theming styles to the Material 3 SCSS API), but I can't figure out how to define typography scale levels (font sizes) with the new API. It used to be done like this:
$my-custom-typography-config: mat.m2-define-typography-config(
  $headline-1: mat.m2-define-typography-level(112px, 112px, 300, $letter-spacing: -0.05em),
  $headline-2: mat.m2-define-typography-level(56px, 56px, 400, $letter-spacing: -0.02em),
  $headline-3: mat.m2-define-typography-level(45px, 48px, 400, $letter-spacing: -0.005em),
  $headline-4: mat.m2-define-typography-level(34px, 40px, 400),
  $headline-5: mat.m2-define-typography-level(24px, 32px, 400),
  // ...
);

But i can't find anything similar in the new theming docs. The best I've found is this: https://material.angular.io/guide/typography#type-scale-levels but it doesn't provide an example.
How can I do this?