剛?cè)肟觟onic3,就碰到Template parse errors:'xxx' is not a known element這個(gè)錯(cuò)誤颈墅。愣是搗鼓了半天章母,才解決自定義組件問題。下面上解決方案:
1 全局中引入自定義組件
1.1 創(chuàng)建一個(gè)組件
ionic g component ion-test
之后目錄會(huì)生成這幾個(gè)文件
1.2 新建對(duì)應(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 某個(gè)頁面中引入自定義組件(含懶加載)
2.1 創(chuàng)建一個(gè)組件(與1.1相同)
2.2 新建對(duì)應(yīng)組件的module.ts文件(與1.2相同)
2.3 新建about.module.ts(因?yàn)楸敬卧赼bout頁面上使用自定義組件)
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)建一個(gè)組件后,在components文件夾中會(huì)生成一個(gè)components.module.ts文件察滑,如果在使用多個(gè)自定義組件到時(shí)候打厘,可以將這些組件一起放到components.module.ts中,最后引入這個(gè)文件即可贺辰,就不用單獨(dú)為每個(gè)組件寫個(gè)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{}
萌新入坑嵌施,一知半解,如有錯(cuò)誤先舷,歡迎指出艰管!