2

I am attempting to define a TypeScript class called NavItem that I want to hold a title and url. I find that if I define this class and instantiate it using object notation {title: "foo", url: "bar"} it works perfectly, but as soon as I add a constructor (even if I don't immediately use it) it completely breaks:

import {Component, Input} from 'angular2/core'

@Component({
    selector: 'nav-item',
    templateUrl: './views/navitem.html',
})
export class NavItem {
    @Input() title: String = "default title";
    @Input() url: String;

    // if I comment the following out it works fine:
    constructor(inTitle: String, inUrl: String) {
        this.title = inTitle;
        this.url = inUrl;
    }
}

If I put the constructor in, I get this in my page:

EXCEPTION: No provider for String! (NavItem -> String) in [navItems in TopNav@2:11]

2 Answers 2

3

If I put the constructor in, I get this in my page:

This is because angular is supposed to instantiate the controller for you. You don't do new FooController, angular does. So any constructor parameters must have a corresponding provider registered with angular.

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

1 Comment

I see. I think my problem is I need to split up my model and view. I am treating NavItem as both a model and a view (a view with properties), and that seems to be a bad idea with Angular.
2

The constructor is used for DI with components. If you want to pass in the values of title and url you would do the following.

<nav-item [title]="Sometitle" [url]="http://someurl.com">

Angular will hook it up for you

Comments

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.