1

I have downgrade a component written in Angular2 + Typescript. Now I want to use it in simple angular 1 app, But the js file compiled from Typescript is using 'import' and I get from browser it is not supported. What I have missed?

This is a simple angular 2 componenet:

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'hello-world',
  template: `
    <p>
      hello from angular 2!
    </p>
  `,
  styles: []
})
export class HelloWorldComponent implements OnInit {

  constructor() { }

  ngOnInit() {
  }


}


import * as angular from 'angular';
import { downgradeComponent } from '@angular/upgrade/static';

angular.module('dannyApp', [])
  .directive(
    'helloWorld',
    downgradeComponent({component: HelloWorldComponent}) as angular.IDirectiveFactory
  );

This is the simple angular1 app tring to use this angular 2 component above:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">

    <script src="https://ajax.googleapis.com/ajax/libs/angularjs/1.5.7/angular.min.js"></script>
    <script src="dist\out-tsc\app\hello-world\hello-world.component.js"></script>

  <script>
      angular.module('app', [])

        .controller('FrameController', ['$injector', function($injector) {
          var vm = this;
          vm.message = 'Hello from angular 1';

        }]);

    </script>

    <title>Title</title>
</head>
<body ng-app="app">

<div id="body">
  <div ng-controller="FrameController as vm">
    {{vm.message}}
  </div>
  <!-- the angular 2 componenet -->
  <hello-world></hello-world>
</div>

</body>
</html>

The browser error: Uncaught SyntaxError: Unexpected token import on the line:

import { Component } from '@angular/core';
AngularOne
  • 2,760
  • 6
  • 32
  • 46
  • after adding require.js to the html, now I get another error: Module name "@angular/core" has not been loaded yet for context: _. Use require([]) – AngularOne Jan 26 '17 at 22:33
  • Not sure what else I need to add to my angular 1 app. the file of angualr2 component need more than that? any one did this and it worked for him? – AngularOne Jan 27 '17 at 12:05

1 Answers1

1

Make sure you have compiled your Typescript component to ES5. Your code looks like ES6/Typescript.

Check your tsconfig.json and make sure target: "es5".

vincic
  • 23
  • 5
  • found the file in es5. but now there is error about 'require' is not defined – AngularOne Jan 26 '17 at 21:56
  • added 'require.js' and it helped. but what it means now: Module name "@angular/core" has not been loaded yet for context: _. Use require([]) From where he gets that? – AngularOne Jan 26 '17 at 22:10