MALIK MAHSAM KHAN
MALIK MAHSAM KHAN

Reputation: 35

TypeError: Cannot read property 'length' of undefined in angular 4

TypeError: Cannot read property 'length' of undefined in angular 4

this is code export class UserComponent implements OnInit{

  roles:IUserRole[];
  sourseRoles: SelectedItem[];
  selectedRole:any;

BindRoles() {
    this.sourseRoles= [];
    this.sourseRoles.push({ label: "Assign Role", value: null });
    if (this.roles.length > 0) {
      for (let role of this.roles) {
        this.sourseRoles.push({ label: role.Title, value: role.UserRoleId })enter image description here
      }
    }
  }
----------

this is code

this.appServiceManager.libGet("Role") .subscribe((role: any) => { this.selectedRole= [];

           this.selectedRole = role;
           this.sourseRoles.push({ label: this.selectedRole.Title, value: this.selectedRole.UserRoleId })
         },
         (error: any) => {
           this.msgs = [];

           this.msgs.push({ severity: 'error', summary: 'Error Message', detail: error });
         });
----------
<label for="password">User Role</label>
 <p-dropdown name="Title" #Title="ngModel" required (click)="BindRoles()" 

 [(ngModel)]="selectedRole" id="dropdown" [options]="sourseRoles"

 [autoWidth]="false"></p-dropdown>

 <div *ngIf="registerForm.submitted && !Title.valid" class="help-block">Role 
 Information is required</div>

----------

Upvotes: 0

Views: 2193

Answers (2)

Anshuman Jaiswal
Anshuman Jaiswal

Reputation: 5462

export class UserComponent implements OnInit {
    roles: IUserRole[] = [];     <======= Initialize it =========>
    sourseRoles: SelectedItem[]; <======= Declaration was incorrect =========>
    selectedRole: any;

    BindRoles() {
      if (this.roles.length > 0) {
        for (let role of this.roles) {
          this.sourseRoles.push({ label: role.Title, value: role.UserRoleId })
        }
      }
    }
}

Upvotes: 1

Phil Boyd
Phil Boyd

Reputation: 390

I don't see this in the TS code:

sourseRoles

I see your roles and selectedRole

Upvotes: 0

Related Questions