Home > other >  Can't access class attribute within html and angular
Can't access class attribute within html and angular

Time:07-21

For some reason I can't access a class attribute when looping a list in html inside a angular's ngFor.

The error I'm getting is Property 'User' does not exist on type 'AppComponent', when I've clearly imported the file and I'm using it without any problems inside app.component.ts.

At the moment I have this, which is creating the error in User.filteredusers. Also, I've included the Users class in the typescript file I'm using.

app.component.html

<tr *ngFor="let user of User.filteredUsers |
    paginate: {
      itemsPerPage: resultsPerPage,
      currentPage: page,
      totalItems: totalLength
    }">
  <th scope="row">{{ user.id }}</th>
  <td>{{ user.name }}</td>
  <td>{{ user.contact }}</td>
  <td>{{ user.login }}</td>
</tr>

app.component.ts

// ...
import { User } from './user.model';
// ...

user.model.ts

export class User{
    // ...
    static filteredUsers = new Array<User>();
    // ...

CodePudding user response:

What i can see is that you are trying to access the class "User" in your app.component.html. You will have to define a variable in you app.component.ts from type "User" and than you can access the variable:

Here an example:

export class Document implements OnInit {
  user: User;


Update So i tried it myself, and it worked the way i told. Even if a variable in a class is static, you cannot access the class itself in html without declaring a variable in the component of the template.

Solution 1 user.component.ts

import {Component} from "@angular/core";

@Component({
  selector: 'app-login',
  templateUrl: './user.component.html',
  styleUrls: ['./user.component.scss'],
})

export class UserComponent {
  static filteredUsers = ["test","test2"];
}

app.component.ts

import { Component } from '@angular/core';
import {UserComponent} from "./user/user.component";

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  user = UserComponent;
}

app.component.html

<div *ngFor = "let user of user.filteredUsers">
  {{user}}
</div>

**Solution 2:** Another way would be to create a function in your app.component.ts where you access the "User.filteredUsers" and return them.

app.component.ts

export class AppComponent {
  getFilteredUser(){
    return UserComponent.filteredUsers
  }
}

app.component.html

<div *ngFor = "let user of getFilteredUser()">
  {{user}}
</div>

  • Related