简体   繁体   中英

Default array value to class constructor angular 2

class DateComponent {
  constructor(public months:string[] = [],public days:number[] = [] , public years:number[] = []) { }

};

This is giving me error in Chrome. Says "=" is invalid. I am using angular 2 and typescript and webpack dev server.

How can i pass values to the parameters in constructor?

Like Harry says in the comment, defining class members in the constructor is reserved for dependency injection in Angular 2.

I'd suggest moving those out of the constructor:

class DateComponent {
  public months: Array<string> = [];
  public days: Array<string> = [];
  public years: Array<string> = [];

  constructor() { 

  }
}

if you want optional parameter of constructor you must add "?". But the parameter of the object must define out of constructor.

In angular2 u will see that some parameter define in constructor but this have use in annotation (@Component, @Directive,...) that's define there as class property.

if i understand correct you want something like this:

class DateComponent {
      public months: [] = [];
      public days: [] = [];
      public years: [] = [];

      constructor(_months?:string[],_days?:number[], _years?:number[]) {
       this.months = _months;
       this.days = _days;
       this.years = _years;
     }

    };

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM