ionic3自定义组件

刚入坑ionic3,就碰到Template parse errors:'xxx' is not a known element这个错误。愣是捣鼓了半天,才解决自定义组件问题。下面上解决方案:

1 全局中引入自定义组件

1.1 创建一个组件

ionic g component ion-test
之后目录会生成这几个文件


1.2 新建对应组件的module.ts文件

ion-test.module.ts


import { NgModule } from '@angular/core';

import {IonTestComponent} from './ion-test';

import {IonicModule} from 'ionic-angular';

@NgModule({

declarations:[IonTestComponent],

imports:[IonicModule],

exports:[IonTestComponent]

})

export class IonTestModule{}

1.3 全局中导入该组件

在app.module.ts导入ion-test.module.ts
①在app.module.ts 头部插入
import { IonTestModule } from '../components/ion-test/ion-test.module'
②在imports:[]中插入IonTestModule


1.4 使用该组件

在about.html中使用组件<ion-test></ion-test>



效果图:


2 某个页面中引入自定义组件(含懒加载)

2.1 创建一个组件(与1.1相同)

2.2 新建对应组件的module.ts文件(与1.2相同)

2.3 新建about.module.ts(因为本次在about页面上使用自定义组件)

about.module.ts



import { NgModule } from '@angular/core';

import { IonTestModule } from '../../components/ion-test/ion-test.module';

import { IonicPageModule } from 'ionic-angular';

import { AboutPage } from './about'

@NgModule({

declarations:[AboutPage]

,imports:[

IonicPageModule.forChild(AboutPage),

IonTestModule

]

,exports:[AboutPage]

})

export class AboutModule{}

2.4 在about.ts添加@IonicPage

about.ts

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

import { NavController } from 'ionic-angular';

import { IonicPage } from 'ionic-angular/navigation/ionic-page';

@IonicPage({name:'about-page'})

@Component({

selector:'page-about',

templateUrl:'about.html'

})

export class AboutPage{

constructor(publicnavCtrl:NavController) {

}

}

2.5 在about.html使用该组件(与1.4相同)

2.6 在app.module.ts中删除AboutPage声明

2.7 修改tabs.ts

去掉AboutPage的导入,用字符串'about-page'来代替原来变量


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

import { ContactPage } from '../contact/contact';

import { HomePage } from '../home/home';

@Component({

templateUrl : 'tabs.html'

})

export class TabsPage{

tab1Root=HomePage;

tab2Root='about-page';

tab3Root=ContactPage;

constructor() {

}

}

2.8 完成,可看到如1.4中的效果图

3 关于components.module.ts

创建一个组件后,在components文件夹中会生成一个components.module.ts文件,如果在使用多个自定义组件到时候,可以将这些组件一起放到components.module.ts中,最后引入这个文件即可,就不用单独为每个组件写个xx.moudle.ts。


import { NgModule } from '@angular/core';

import { IonTestComponent } from './ion-test/ion-test';

……

……

import { IonicModule } from 'ionic-angular';


@NgModule({

declarations:[

IonTestComponent,

……

……

],

imports : [ IonicModule ],

exports:[

IonTestComponent

……

……

]

})

export class ComponentsModule{}

萌新入坑,一知半解,如有错误,欢迎指出!

最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

推荐阅读更多精彩内容