ionic3自定義組件

剛?cè)肟觟onic3,就碰到Template parse errors:'xxx' is not a known element這個錯誤。愣是搗鼓了半天,才解決自定義組件問題。下面上解決方案:

1 全局中引入自定義組件

1.1 創(chuàng)建一個組件

ionic g component ion-test
之后目錄會生成這幾個文件


1.2 新建對應(yīng)組件的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 全局中導(dǎo)入該組件

在app.module.ts導(dǎo)入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 創(chuàng)建一個組件(與1.1相同)

2.2 新建對應(yīng)組件的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的導(dǎo)入,用字符串'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 關(guān)于components.module.ts

創(chuàng)建一個組件后,在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{}

萌新入坑,一知半解,如有錯誤,歡迎指出!

最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容