Reputation: 8922
I m actually making the angular.io quickstart and I need now to split my component into different files.
The problem is that I dont know at all how to do it, and it's not explained in the dev preview doc.
Can you help ?
I simply have two components (the main in app.js, and another one which only list informations)
Thanks for advance
Upvotes: 6
Views: 11611
Reputation: 4540
Agree, this is not well explained and a lot of examples only use a single component or components in a single file. This is an example I am building which uses (currently) 2 components in separate files and is about as simple as I can make it...
https://github.com/mdausmann/angular2-canvas
Essentially, you need to export the sub-component from it's module...
export default NoteComponent;
and import it into the composing or parent module...
import NoteComponent from "note";
Oh, this import/export thing is ES6 module syntax, great ref here
Hope this helps.
Upvotes: 6
Reputation: 561
According to official ref just change the template
property to templateUrl
:
@Component({
selector: 'my-app',
//template: `Hi, {{name}}`,
templateUrl: './app.html'
})
export class AppComponent { name = 'Peter'; }
Upvotes: 0
Reputation: 734
Here is an example with making folder for each component.
If you app.ts
is at the root, you can make a folder/components/
and put each component into a separate sub-folder, keeping .ts, .html and .css file of each component together in its folder.
So if you have a component called 'Actions', you would put actions.ts
, actions.html
and actions.css
into a folder /components/actions/
.
In actions.ts
you mention this:
@Component({
selector: 'actions'
}
@View({
templateUrl: './components/actions/actions.html'
})
export class Actions { ... }
And to include actions
in app.ts:
import {Actions} from '../../components/actions/actions';
@View({
templateUrl: 'app.html',
directives: [Actions]
})
And in app.html just include the selector of actions:
<actions></actions>
Upvotes: 0
Reputation: 7244
This example is ES6 but the same principles apply for any language. You just use imports, make sure to transpile your code into the appropriate files and configure the module loader appropriately.
Here is an example http://plnkr.co/edit/F2gNplix1tBSg3iZmkd0?p=preview
This example has three files: main.es6.js
, a1.es6.js
and a2.es6.js
- the plunker system transpiles these files into main.js
, a1.js
and a2.js
The System options in index.html
tell the module loader how to find these, so that import {A1} from 'a1'
finds the class from the transpiled a1.js
file.
Upvotes: 2