【发布时间】:2016-10-26 22:16:31
【问题描述】:
在Ionic2 / Angular2中:我试图弄清楚如何将带有自己的选择器的图形添加到页面中。
从 Ionic2 教程项目开始,我添加了 2 个元素:“MyPage”和“MyGraphDiagram”。我想在“MyPage”中使用“MyGraphDiagram”。
在“[MyProject]/src/app/app.module.ts”我有:
import ...
import { MyPage } from '../pages/my/my';
import { MyGraphDiagram } from '../pages/my/graph-components/my-graph';
@NgModule({
declarations: [
MyApp,
HelloIonicPage,
ItemDetailsPage,
ListPage,
MyPage,
MyGraphDiagram
],
imports: [
IonicModule.forRoot(MyApp)
],
bootstrap: [IonicApp],
entryComponents: [
MyApp,
HelloIonicPage,
ItemDetailsPage,
ListPage,
MyPage,
MyGraphDiagram
],
providers: []
})
export class AppModule {}
FIRST:在这里,如果我编译项目,则声明节点中的 MyGraphDiagram 存在问题(我还认为我已经正确实现了 MyGraphDiagram)。
在 [MyProject]/src/app/app.component.ts 中,它保持不变,只是将根页面替换为:rootPage: any=MyPage。
在“[MyProject]/src/pages/my/graph-components/my-graph.ts”中(这是thread的副本):
import {Component, View, Input, ViewChild, ElementRef} from 'angular2/core';
@Component({
selector: 'my-graph',
})
@View({
template: `<canvas #myGraph class='myGraph'
[attr.width]='_size'
[attr.height]='_size'></canvas>`,
})
export class MyGraphDiagram {
private _size: number;
// get the element with the #myGraph on it
@ViewChild("myGraph") myGraph: ElementRef;
constructor(){
this._size = 150;
}
ngAfterViewInit() { // wait for the view to init before using the element
let context: CanvasRenderingContext2D = this.myGraph.nativeElement.getContext("2d");
// happy drawing from here on
context.fillStyle = 'blue';
context.fillRect(10, 10, 150, 150);
}
get size(){
return this._size;
}
@Input () set size(newValue: number){
this._size = Math.floor(newValue);
}
}
然后最后在“[MyProject]/src/pages/my/my.ts”下:
import {Component} from '@angular/core';
import { NavController, NavParams } from 'ionic-angular';
import { MyGraphDiagram } from '/graph-component/my-graph'
@Component({
selector:'my-page',
template: 'my.html'
})
export class MyPage {
constructor(public navCtrl: NavController, public navParams: NavParams){
}
}
还有“[MyProject]/src/pages/my/my.html”:
<ion-header>...
</ion-header>
<ion-content>
<my-graph></my-graph>
</ion-content>
如果我运行 CLI “ionic run android”:
如果我将 MyGraphDiagram 留在“[MyProject]/src/app/app.module.ts”的 declaration 节点中,则 lint 部分不会通过。它抛出一个错误:
错误:模块声明的意外值“MyGraphDiagram” '应用模块'
如果我采用 declartion 节点的 MyGraphDiagram,lint 部分会通过,但构建会抛出该错误:
'my-graph' 不是已知元素:
[00:08:06] 1. 如果 'my-graph' 是 Angular 组件,则验证 它是这个模块的一部分。 [00:08:06] 2. 如果 'my-graph' 是 Web 组件然后将“CUSTOM_ELEMENTS_SCHEMA”添加到 '@NgModule.schema'
一些更新: 如果我运行 CLI“离子服务”:
TypeScript Transpile 失败并出现以下错误:
找不到名称“ElementRef”
L13: myGraph: ElementRef;
【问题讨论】: