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]
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.
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
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.