user3573738
user3573738

Reputation:

How to fill class properties from model Angular?

I have an Class Car with some properties:

public id: number;
public roleId: number;
public roleName: string;

Also I have the same object {id: 1, roleId: 1, roleName: 4}

How to assign this object to each property?

I dont want to use:

this.id = obj.id;
this.roleName = obj.roleName;
this.roleId = obj.roleId;

Upvotes: 1

Views: 1286

Answers (2)

Vega
Vega

Reputation: 28708

Try this syntax:

class Car {
    public id?: number;
    public roleId?: number;
    public roleName?: string;

    constructor(values: Car) {
      Object.assign(this, values);
    }
}

and use it:

 let car = new Car({id: 1, roleId: 1, roleName: "4"});

Demo StackBlitz

DEMO plunker

Upvotes: 1

Rohan Fating
Rohan Fating

Reputation: 2133

Use object.assign property.

Object.assign(new Car(), {
        id: obj.id,
        roleName : obj.roleName,
        roleId : obj.roleId
    })

Upvotes: 2

Related Questions