【问题标题】:How can i use the ionic 2 's components in angular 2 project?如何在 angular 2 项目中使用 ionic 2 的组件?
【发布时间】:2017-03-20 09:17:04
【问题描述】:

我想在我的 angular 2 项目的功能模块中使用 ionic 2。我想在我的某些组件中使用离子的组件或标签。我所做的每一件事,但我得到了这个错误 EXCEPTION: Expected to not be in Angular Zone, but it is!

谁能告诉我如何在 angular 2 项目中使用 ionic 2 的组件而不是使用 ionic-cli 创建一个新的组件?

【问题讨论】:

    标签: angular ionic2


    【解决方案1】:

    首先使用创建一个angular 2项目

    ng new myapp --style=scss
    

    然后

    cd myapp
    npm install --save ionic-angular ionicons
    

    您可能会收到一些警告,例如

    npm WARN ionic-angular@2.0.0-rc.2 requires a peer of @angular/common@2.1.1 but none was installed.
    npm WARN ionic-angular@2.0.0-rc.2 requires a peer of @angular/compiler@2.1.1 but none was installed.
    ...
    

    即使有警告,它也可以工作,但如果您希望摆脱所有这些警告,您可以检查 ionic-angular 声明了哪些 peerDependencies:

    npm view ionic-angular peerDependencies
    

    然后相应地更新 package.json 中的版本和npm install. 你也可以删除 @angular/router,因为 Ionic 提供了自己的导航机制。

    npm uninstall --save @angular/router
    

    然后ng serve

    在您的项目中使用 Ionic 的下一步是更改 src/app/app.module.ts 以导入 IonicModule 而不是 Angular 的 BrowserModule,并引导 IonicApp:

    import { NgModule } from '@angular/core';
    import { IonicApp, IonicModule } from 'ionic-angular';
    
    import { AppComponent } from './app.component';
    
    @NgModule({
      imports: [ IonicModule.forRoot(AppComponent) ],
      declarations: [ AppComponent ],
      bootstrap: [ IonicApp ]
    })
    export class AppModule { }
    

    IonicApp 组件有 ion-app 作为其选择器,因此您还需要修改 src/index.html 替换为 .

    要使项目结构与 Ionic CLI 生成的结构有些相似,请创建一个 src/theme 文件夹,然后下载并放入以下两个文件:ionic.scss 和 variables.scss。

    最后通过编辑 angular-cli.json 将它们包含在构建过​​程中,以首先在 app 内的样式中加载 variables.scss:

    "styles": [
      "theme/variables.scss",
      "styles.scss"
    ],
    

    请注意,您必须重新启动 ng serve 才能使此更改生效。

    拥有一个基本的 Ionic 应用程序的最后一步是创建一个页面组件,并使用 ion-nav 将其加载到 AppComponent 中。

    为此,创建一个 src/pages 文件夹,其中包含一个 home.page.ts 文件,其中包含例如

    import { Component } from '@angular/core';
    
    @Component({
      selector: 'page-home',
      templateUrl: 'home.page.html'
    })
    export class HomePage {
    
      message = 'Welcome!';
    
    }
    

    以及home.page.html中对应的带有基本Ionic页面的模板,包括标题和内容:

    <ion-header>
      <ion-navbar>
        <ion-title>Ionic App</ion-title>
      </ion-navbar>
    </ion-header>
    <ion-content padding>
      {{ message }}
    </ion-content>
    

    您可以从ionic2-with-angular-cli 获取完整文档。希望对您有所帮助。

    【讨论】:

      猜你喜欢
      • 2016-06-26
      • 2017-12-23
      • 1970-01-01
      • 1970-01-01
      • 2018-04-10
      • 2017-04-21
      • 2016-04-18
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多