Ranger
Ranger

Reputation: 1174

Using ngOnInit() instead of a constructor; @Input() undefined

First of all if this is horrible design, I'm more than happy to change.

In my index.html I, in the body, have:

<month [year]="2016" [monthOfYear]="4">Loading...</month>

month.component.ts is then:

import { Component, Input, OnInit } from '@angular/core';
import { DayComponent } from '../day/day.component';
import * as Models from '../../../models/_models';

@Component({  
  selector: 'month',
  moduleId: module.id,
  templateUrl: 'month.component.html',
  styleUrls: ['month.component.css'],
  directives: [DayComponent]
})

export class MonthComponent {  
  name: string;
  days: Models.Day[];
  @Input('year') year: number;
  @Input('monthOfYear') monthOfYear: number;
  month: Models.Month;

  ngOnInit() {
    this.month = new Models.Month(this.year, this.monthOfYear);
    this.name = this.month.getMonthName();
    this.days = this.month.days;
  }
}

...And ngOnInit() is called correctly. However at the time of calling (or perhaps ever, but I don't know how to determine that) both year and monthOfYear are undefined.

How do I ensure the values are passed in at ngOnInit(), or is there a better pattern to accomplish this?

Upvotes: 2

Views: 1832

Answers (2)

trey-jones
trey-jones

Reputation: 3437

So this is actually quite simple, but not clear from the tutorial/docs.

Here is the solution:

<month year="2016" monthOfYear="4">Loading...</month>

The square brackets around attributes signify that the component should treat those as data bindings to the parent component. So if you wanted to pass those values from the parent, you would do the following:

<month [year]="year" [monthOfYear]="month">Loading...</month>

In your case you are assigning string literals, and so the square brackets aren't needed. Also, you should declare that your component implements OnInit, but that doesn't seem to have any bearing on the execution.

Upvotes: 5

Picci
Picci

Reputation: 17762

If I understand right, you try to pass some values from index.html to a Component (which in this case becomes the root component ). I am not sure this can work since Angular gets bootstrapped by the root component and can not serve index.html (which is the page that hosts Angular).

Normally in index.html you have a root (let's say AppComponent). AppComponent contains your components (eg MonthComponent). AppComponent CAN pass values to MonthComponent.

I hope this helps

Upvotes: 2

Related Questions