0

user.ts

export class User {
  ....
  roles: Role[]
}

<select name="roles" class="form-control role_select" [(ngModel)]="user.roles">
        <option value="null" >Select role</option>
        <option *ngFor="let role of roles" [value]="role.id">  
            {{role.title}}
        </option>

      </select>

It works fine but not selected the role. Data of user comes like this

Roles: Array[1]
username: "vsdfsdfsdfds"

Update code , issue is that when I set user.roles it gives an Property 'Roles' does not exist on type 'User'

setUser(user: User): void {
  this.user = user;
  this.user.roles = user.Roles;
}

public ngOnInit(): void {        
  this.userSubscription =    this.userService.getuserdetail(this.route.params['_value']['id']).subscribe(user => {            
  this.setUser(user);                              
}); 
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
Haseeb Ahmad
  • 7,914
  • 12
  • 55
  • 133

3 Answers3

0

Something like

ngOnInit() {
  this.user.roles = this.Roles[0];
}
Günter Zöchbauer
  • 623,577
  • 216
  • 2,003
  • 1,567
0

In this case I would use interfaces, there is no need to use classes.

So use interfaces instead:

export interface User {
  username: string;
  roles: Role[];
}

and your can skip the setUser-method altogether, you can assign the values to user in the subscription:

.subscribe(user => {
  this.user = {username: user.username, roles: user.Roles}
});

You end up with wrong content of user when you are first assigning the content of the user AND assigning roles after that. When I tried it, I ended up with an Object with both an Roles and roles array in the object.

Then your template would need some changes, since data is coming async we will wrap the select in *ngIf as well.

<div *ngIf="user">
  <select [(ngModel)]="user.roles">
    <option value="null" >Select role</option>
    <option *ngFor="let role of user.roles">  
        {{role.title}}
    </option>
  </select>
</div>

Notice the iteration of the roles is *ngFor="let role of user.roles"

Hope this helps!

Community
  • 1
  • 1
AT82
  • 71,416
  • 24
  • 140
  • 167
-1

Argument of that function cannot be of class User, because it has Roles property. In User class you have only roles property. The size of the letters is important in JS and TS.

setUser(user: any): void {
  this.user = user.username; // 
  this.user.roles = user.Roles;
}