I've played with the angular 2 demo on angular.io. Now I want to create a new component and use it inside my app.
My current app:
import {Component, Template, bootstrap} from 'angular2/angular2';
import {UsersComponent} from './components/users/component.js';
// Annotation section
@Component({
selector: 'my-app'
})
@Template({
url:"app.html"
})
// Component controller
class MyAppComponent {
newName:string;
names:Array<string>;
constructor() {
this.name = 'Florian';
}
showAlert(){
alert("It works");
}
addName(){
names.push(newName);
newName = "";
}
}
bootstrap(MyAppComponent);
My component:
import {Component, Template, bootstrap} from 'angular2/angular2';
// Annotation section
@Component({
selector: 'users'
})
@Template({
url:"./template.html"
})
// Component controller
class UsersComponent {
newName:string;
names:Array<string>;
constructor() {
}
addName(){
names.push(newName);
newName = "";
}
}
I'm not sure if the syntax of my user component is correct at all.
My app template:
<h1>Hello {{ name }}</h1>
<h2>{{2+2}}</h2>
<hr />
<button (click)="showAlert()">Click to alert</button>
<users></users>
So how do I wire up the User component?
The error I get in the console:
"Error loading "components/users/component.js" at <unknown>↵Error loading "components/users/component.js" from "app" at http://localhost:8080/app.es6↵Cannot read property 'replace' of undefined"
The Angular framework allows us to use a component within another component and when we do so then it is called Angular Nested Components. The outside component is called the parent component and the inner component is called the child component.
In the above code, you can see how it has been nested with the StudentList component. This is how we can create nested component in Angular 2.
Angular calendar demo has two nested components (calendar and calendar-cell) https://github.com/djsmith42/angular2_calendar.git . From what I can see there your MyAppComponent should reference Users component from @Template's directives list, like this:
@Template({
url: System.baseURL+'app/components/calendar/calendar.html',
directives: [
Foreach,
If,
CalendarCell
]
})
In this link of Angular2
web https://angular.io/docs/ts/latest/tutorial/toh-pt3.html# you can see that adding directives: [...]
inside of @Components
for example:
@Component({
selector: 'my-app',
directives: [UsersComponent]
})
but otherwise the link use template inside the component, do not know if this will work if you use @Template({ url:"app.html"})
outside component.
you can watch the file name app.appcomponet.ts
for more details, hopefully help.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With