我创建了一个Angular 2组件,我想在现有的Angular 1应用程序中使用它。我按照Angulars网站上的说明进行操作:https://angular.io/docs/ts/latest/guide/upgrade.html
Angular 2组件未呈现,并且应用程序不会抛出任何错误。以下是已添加的文件。
bootstrap.ts
import 'zone.js/dist/zone';
import 'reflect-metadata';
import { bootstrapCommon } from './../components/bootstrap.ts';
import { upgradeAdapter } from './../components/upgradeAdapter.ts';
import { A2Component } from './../components/a2component/a2.component.ts';
declare var angular: any;
angular.element(document).ready(function () {
upgradeAdapter.bootstrap(document.documentElement, ['client'], { strictDi: true });
angular.module('client')
.directive('aTwoComponent',
upgradeAdapter.downgradeNg2Component(A2Component));
});
a2.component.ts
/// <reference path="../../../node_modules/@angular/core/index.d.ts" />
/// <reference path="../../../node_modules/@angular/platform-browser/index.d.ts" />
import {Component, OnInit} from '@angular/core';
@Component({
selector: 'a-two-component',
template: '<h1>Angular 2 component!</h1>'
})
export class A2Component implements OnInit {
constructor() {
console.log('a2 component constructor');
}
ngOnInit() {
console.log('a2 component oninit');
}
}
这是'客户'模块的当前角度1注册,尚未修改。
(function () {
'use strict';
angular.module('client', ['ui.router', 'common', 'orders', 'reports', 'schedules']);
angular.module('client')
.config(config);
function config($stateProvider, $urlRouterProvider, $httpProvider) {
$urlRouterProvider.otherwise('/');
$stateProvider
.state('home', {
url: '/',
title: 'Client Home',
template: '<sb-client-home></sb-client-home>',
data: {
authorizedRoles: ['client']
}
});
}
})();
最后是index.html,唯一的区别是ng-app已从html标签中删除,我添加了角度2元素(a-two-component)。
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8" />
<meta http-equiv="X-UA-Compatible" content="IE=edge, chrome=1" />
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>{{title || 'Home'}}</title>
<!--INJECT:vendor-css-->
<!--END INJECT-->
<link rel="stylesheet" href="/css/main.css">
<link rel="stylesheet" href="/css/client.css">
</head>
<body id="bootstrap-overrides">
<sb-client-layout></sb-client-layout>
<a-two-component></a-two-component>
<!--INJECT:vendor-js-->
<!--END INJECT-->
<!--inject:js-->
<!--endinject-->
</body>
</html>
答案 0 :(得分:1)
模块的引导应在所有组件降级并注册后完成。在bootstrap.ts中交换这两行代码可以解决问题。
angular.module('client')
.directive('aTwoComponent',
<angular.IDirectiveFactory>upgradeAdapter.downgradeNg2Component(MyComponent));
upgradeAdapter.bootstrap(document.documentElement, ['client'], { strictDi: true });