0

In an angular 4 model, I have some typescript code that looks like this:

export class Thing {
  public a: number;
  public b: number;
  public c: number;
  constructor(a, b, c){
    this.a = a || 0;
    this.b = b || 0;
    this.c = c || 0;
    }
}

This seems an obvious place to use a loop, or something simpler than declaring variables a, b, and c and then following up with assigning a, b, and c, via the constructor.

Not sure how to get that done though.

1 Answer 1

2

You can also do this. Declare your variables via access modifiers in the constructor. This will automatically create your fields with that access modifiers and assign to them the values which you pass. Also you can assign default values to the parameters, if the value passed will be undefined.

export class Thing { 
   constructor(public a: number = 0, 
               public b: number = 0, 
               public c: number = 0) {

   }
}

const thing = new Thing(1, 2);
// thing.a = 1
// thing.b = 2
// thing.c = 0 - default value

One Note also. Angular 5 is released. You can use it.

Sign up to request clarification or add additional context in comments.

1 Comment

Thank you. I believe that that's solution I'm most after. And yes, I'm also on angular 5 right now. My miss type.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.