Note new repo and install: https://github.com/wwwalkerrun/nativescript-ngx-magic
Magically drop a NativeScript app into your existing Angular2 web application and reuse all your code.*
You will be adding NativeScript views, but you already knew that.
npm i nativescript-ng2-magic --save
Component
from nativescript-ng2-magic
instead of @angular/core
. Why?.tns.html
(and/or styles ending with .tns.css
) for each of your component's. How?A sample root component, app.component.ts:
import {Component} from 'nativescript-ng2-magic';
@Component({
selector: 'app',
templateUrl: './app.component.html'
})
export class AppComponent {}
You will need to have fully completed steps 1 and 2 above.
Run your app in the iOS Simulator with:
npm run start.ios
Run your app in an Android emulator with:
npm run start.android
Welcome to the wonderfully magical world of NativeScript!
Based on our example above, assume app.component.html
looks like this:
<main>
<div>This is my root component</div>
</main>
You would then create a new file in app.component.tns.html
like this:
<StackLayout>
<Label text="This is my root component"></Label>
</StackLayout>
You can also use platform specific views if desired with the platformSpecific
Component metadata:
import {Component} from 'nativescript-ng2-magic';
@Component({
selector: 'app',
templateUrl: './app.component.html',
platformSpecific: true
})
export class AppComponent {}
Then you could create separate views for iOS and Android:
app.component.ios.html
app.component.android.html
You can learn more about NativeScript view options here.
You can also install helpful view snippets for VS Code here or Atom Editor here.
You can learn more here about how this setup works and why.
Component
from nativescript-ng2-magic
is identical to Component
from @angular/core
, except it automatically uses NativeScript views when your app runs in a NativeScript mobile app.
The library provides a custom Decorator
under the hood.
Feel free to check it out here and it uses a utility here.
You can see more elaborate use cases of this magic with angular2-seed-advanced.
Currently you cannot use custom component decorators with AoT compilation. This may change in the future but for now you can use this pattern for when you need to create AoT builds for the web:
import { Component } from '@angular/core';
// just comment this out and use Component from 'angular/core'
// import { Component } from 'nativescript-ng2-magic';
@Component({
// etc.
After doing the above, running AoT build will succeed. :)
The Component from nativescript-ng2-magic
does the auto templateUrl
switching to use {N} views when running in the {N} app therefore you don't need it when creating AoT builds for the web. However just note that when going back to run your {N} app, you should comment back in the Component
from nativescript-ng2-magic
. Again this temporary inconvenience may be unnecessary in the future.