typescript 如何使 PrimeNG 菜单栏组件工作?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/37980888/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to make PrimeNG Menubar component work?
提问by zho
I'm trying to make a menubar using PrimeNG, based on example from http://www.primefaces.org/primeng/#/menubar
我正在尝试使用 PrimeNG 制作菜单栏,基于http://www.primefaces.org/primeng/#/menubar 的示例
I create something like this:
我创建了这样的东西:
app.component.ts
app.component.ts
import {Component} from '@angular/core';
import {MenuBarComponent} from "./menubardemo.component";
@Component({
selector: 'my-app',
template: `<h1>My First Angular 2 App</h1><demo></demo>`,
directives:[MenuBarComponent] })
export class AppComponent { }
menubardemo.components.ts
menubardemo.components.ts
import {Component, OnInit} from "@angular/core";
import {Menubar, MenuItem} from "primeng/primeng";
@Component({
selector: 'demo',
template: `<p-menubar [model]="items"> </p-menubar>`,
directives: [Menubar] })
export class MenuBarComponent implements OnInit {
private items:MenuItem[];// you know how to fill this in the "OnInit" method
ngOnInit() {
this.items = [
{
label: 'File',
icon: 'fa-file-o',
items: [{
label: 'New',
icon: 'fa-plus',
items: [
{label: 'Project'},
{label: 'Other'},
]
},
{label: 'Open'},
{label: 'Quit'}
]
},
{
label: 'Edit',
icon: 'fa-edit',
items: [
{label: 'Undo', icon: 'fa-mail-forward'},
{label: 'Redo', icon: 'fa-mail-reply'}
]
},
{
label: 'Help',
icon: 'fa-question',
items: [
{
label: 'Contents'
},
{
label: 'Search',
icon: 'fa-search',
items: [
{
label: 'Text',
items: [
{
label: 'Workspace'
}
]
},
{
label: 'File'
}
]
}
]
},
{
label: 'Actions',
icon: 'fa-gear',
items: [
{
label: 'Edit',
icon: 'fa-refresh',
items: [
{label: 'Save', icon: 'fa-save'},
{label: 'Update', icon: 'fa-save'},
]
},
{
label: 'Other',
icon: 'fa-phone',
items: [
{label: 'Delete', icon: 'fa-minus'}
]
}
]
},
{
label: 'Quit', icon: 'fa-minus'
}
];
}
}
after I checked out the data object is printed on the DOM, but the menubar is not showing.
在我检出数据对象后打印在 DOM 上,但没有显示菜单栏。
UPDATE:
更新:
index.html
索引.html
<html>
<head>
<title>Angular 2 QuickStart</title>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<link rel="stylesheet" type="text/css" href="node_modules/primeui/themes/omega/theme.css" />
<link rel="stylesheet" type="text/css" href="node_modules/font-awesome/css/font-awesome.min.css">
<link rel="stylesheet" type="text/css" href="node_modules/primeui/primeui-ng-all.min.css" />
<link rel="stylesheet" href="styles.css">
<!-- Polyfill(s) for older browsers -->
<script src="node_modules/core-js/client/shim.min.js"></script>
<script src="node_modules/zone.js/dist/zone.js"></script>
<script src="node_modules/reflect-metadata/Reflect.js"></script>
<script src="node_modules/systemjs/dist/system.src.js"></script>
<script src="node_modules/primeui/primeui-ng-all.min.js"></script>
<script src="systemjs.config.js"></script>
<script>
System.import('app').catch(function(err){ console.error(err); });
</script>
</head>
<body>
<my-app>Loading...</my-app>
</body>
</html>
package.json
包.json
{
"name": "angular2-quickstart",
"version": "1.0.0",
"description": "QuickStart package.json from the documentation, supplemented with testing support",
"scripts": {
"start": "tsc && concurrently \"tsc -w\" \"lite-server\" ",
"docker-build": "docker build -t ng2-quickstart .",
"docker": "npm run docker-build && docker run -it --rm -p 3000:3000 -p 3001:3001 ng2-quickstart",
"pree2e": "npm run webdriver:update",
"e2e": "tsc && concurrently \"http-server\" \"protractor protractor.config.js\"",
"lint": "tslint ./app/**/*.ts -t verbose",
"lite": "lite-server",
"postinstall": "typings install",
"test": "tsc && concurrently \"tsc -w\" \"karma start karma.conf.js\"",
"tsc": "tsc",
"tsc:w": "tsc -w",
"typings": "typings",
"webdriver:update": "webdriver-manager update"
},
"keywords": [],
"author": "",
"license": "ISC",
"dependencies": {
"@angular/common": "2.0.0-rc.1",
"@angular/compiler": "2.0.0-rc.1",
"@angular/core": "2.0.0-rc.1",
"@angular/http": "2.0.0-rc.1",
"@angular/platform-browser": "2.0.0-rc.1",
"@angular/platform-browser-dynamic": "2.0.0-rc.1",
"@angular/router": "2.0.0-rc.1",
"@angular/router-deprecated": "2.0.0-rc.1",
"@angular/upgrade": "2.0.0-rc.1",
"systemjs": "0.19.27",
"es6-shim": "^0.35.0",
"reflect-metadata": "^0.1.3",
"rxjs": "5.0.0-beta.6",
"zone.js": "^0.6.12",
"angular2-in-memory-web-api": "0.0.7",
"primeng": "1.0.0-beta.7",
"primeui": "4.1.12"
},
"devDependencies": {
"concurrently": "^2.0.0",
"lite-server": "^2.2.0",
"typescript": "^1.8.10",
"typings": "^1.0.4",
"canonical-path": "0.0.2",
"http-server": "^0.9.0",
"tslint": "^3.7.4",
"lodash": "^4.11.1",
"jasmine-core": "~2.4.1",
"karma": "^0.13.22",
"karma-chrome-launcher": "^0.2.3",
"karma-cli": "^0.1.2",
"karma-htmlfile-reporter": "^0.2.2",
"karma-jasmine": "^0.3.8",
"protractor": "^3.3.0",
"rimraf": "^2.5.2"
},
"repository": {}
}
tsconfig.json
配置文件
{
"compilerOptions": {
"target": "es5",
"module": "commonjs",
"moduleResolution": "node",
"sourceMap": true,
"emitDecoratorMetadata": true,
"experimentalDecorators": true,
"removeComments": false,
"noImplicitAny": true,
"suppressImplicitAnyIndexErrors": true
}
}
systemjs.config.js
systemjs.config.js
/**
* System configuration for Angular 2 samples
* Adjust as necessary for your application needs.
*/
(function (global) {
// map tells the System loader where to look for things
var map = {
'app': 'app', // 'dist',
'@angular': 'node_modules/@angular',
'angular2-in-memory-web-api': 'node_modules/angular2-in-memory-web-api',
'rxjs': 'node_modules/rxjs',
'primeng': 'node_modules/primeng'
};
// packages tells the System loader how to load when no filename and/or no extension
var packages = {
'app': {main: 'main.js', defaultExtension: 'js'},
'rxjs': {defaultExtension: 'js'},
'angular2-in-memory-web-api': {main: 'index.js', defaultExtension: 'js'},
'primeng': {defaultExtension: 'js'}
};
var ngPackageNames = [
'common',
'compiler',
'core',
'forms',
'http',
'platform-browser',
'platform-browser-dynamic',
'router',
'router-deprecated',
'upgrade',
];
// Individual files (~300 requests):
function packIndex(pkgName) {
packages['@angular/' + pkgName] = {main: 'index.js', defaultExtension: 'js'};
}
// Bundled (~40 requests):
function packUmd(pkgName) {
packages['@angular/' + pkgName] = {main: '/bundles/' + pkgName + '.umd.js', defaultExtension: 'js'};
}
// Most environments should use UMD; some (Karma) need the individual index files
var setPackageConfig = System.packageWithIndex ? packIndex : packUmd;
// Add package entries for angular packages
ngPackageNames.forEach(setPackageConfig);
// No umd for router yet
packages['@angular/router'] = {main: 'index.js', defaultExtension: 'js'};
var config = {
map: map,
packages: packages
};
System.config(config);
})(this);
typings.json
打字.json
{
"globalDependencies": {
"angular-protractor": "registry:dt/angular-protractor#1.5.0+20160425143459",
"core-js": "registry:dt/core-js#0.0.0+20160602141332",
"jasmine": "registry:dt/jasmine#2.2.0+20160621224255",
"node": "registry:dt/node#6.0.0+20160621231320",
"selenium-webdriver": "registry:dt/selenium-webdriver#2.44.0+20160317120654"
}
}
回答by Andrés
I had the same problem, and searching everywhere, even in this post, I was able to solve it, just configuring a simple empty Route:
我也遇到了同样的问题,到处搜索,即使在这篇文章中,我也能解决它,只需配置一个简单的空Route:
app.module.ts
app.module.ts
import { RouterModule } from '@angular/router';
@NgModule({
...
imports: [ RouterModule.forRoot([]), ... ]
...
})
index.html:
索引.html:
<script>document.write('<base href="' + document.location + '" />');</script>
回答by tanspac
I ran into a similar issue. In my case my application is not using routing, but PrimeNG still requires it. There is an open requestto make the router optional, but PrimeNG hasn't responded to that. So I created my own router service:
我遇到了类似的问题。就我而言,我的应用程序没有使用路由,但 PrimeNG 仍然需要它。有一个开放请求使路由器成为可选,但 PrimeNG 尚未对此做出响应。所以我创建了自己的路由器服务:
export class Router
{
constructor(){}
public navigate(route: any[]):void
{
// Do nothing
}
}
Then I modified my systemjs.config.js
to point @angular/router
to my new router. This worked great and I can use the component without needing the router.
然后我修改了我systemjs.config.js
的指向@angular/router
我的新路由器。这很好用,我可以在不需要路由器的情况下使用该组件。
回答by Sanket
Try importing both Menubar and MenuItem
尝试同时导入 Menubar 和 MenuItem
import {Menubar,MenuItem} from 'primeng/primeng';
As per your menubardemo.components.ts, you are using only MenuItem.
根据您的 menubardemo.components.ts,您仅使用 MenuItem。
回答by Sergio
The documentation is not really complete in this case, you can take a look at the source code and you will find a more complete example: https://github.com/primefaces/primeng/tree/master/showcase/demo/menubar
这种情况下文档不是很完整,你可以看一下源代码,你会发现一个更完整的例子:https: //github.com/primefaces/primeng/tree/master/showcase/demo/menubar
Given that angular2 is based on components, is better if you extract the menubar in one component and then you can reference it from the AppComponent
. For this you first need to create a separate Typescript file of your component, in this case menubardemo.component.ts
:
鉴于 angular2 基于组件,如果您在一个组件中提取菜单栏,然后您可以从AppComponent
. 为此,您首先需要为您的组件创建一个单独的 Typescript 文件,在这种情况下menubardemo.component.ts
:
Then you need to add the @Component
to the MenubarDemoComponent
like this:
然后,你需要添加@Component
到MenubarDemoComponent
是这样的:
import {Component, OnInit} from "@angular/core";
import {Menubar, MenuItem} from "primeng/primeng";
@Component({
selector: 'demo',
template: `<p-menubar [model]="items"> </p-menubar>`,
directives: [Menubar] })
export class MenuBarComponent implements OnInit {
private items:MenuItem[];// you know how to fill this in the "OnInit" method
}
And then add it to the AppComponent
like this:
然后将其添加到AppComponent
这样的:
import {Component} from '@angular/core';
import {MenuBarComponent} from "./menubardemo.component";
@Component({
selector: 'my-app',
template: `<h1>My First Angular 2 App</h1><demo></demo>`,
directives:[MenuBarComponent] })
export class AppComponent { }
One important thing to remember: ALWAYS use " ` " (backtick) when creating a template directly in component's definition, you are using " ' " (single quote) and is incorrect (if your html needs more lines, consider extracting it to other file).
需要记住的一件重要事情:在组件定义中直接创建模板时,始终使用“`”(反引号),您使用的是“'”(单引号)并且是不正确的(如果您的 html 需要更多行,请考虑将其提取到其他文件)。
You are instantiating the component: items = new MenubarDemo()
, that is also incorrect because components are
injected for you automatically, only declare the component in the
directives
field.
您正在实例化组件:items = new MenubarDemo()
,这也是不正确的,因为组件是自动为您注入的,仅在directives
字段中声明组件
。
回答by Tony
Looking at the error "No provider for Router" looks like an issue with PrimeNG component not having angular2 Router configured, but I didn't confirm, it would be nice if anyone digs into this.
查看错误“No provider for Router”看起来像是 PrimeNG 组件没有配置 angular2 Router 的问题,但我没有确认,如果有人深入研究这个会很好。
Anyway, I had this problem, added some basic routing and it worked, so I'm sharing it, it should be something like this:
无论如何,我遇到了这个问题,添加了一些基本的路由并且它起作用了,所以我分享它,它应该是这样的:
main.ts
主文件
import { bootstrap } from '@angular/platform-browser-dynamic';
import { AppComponent } from './app.component';
import { provide } from '@angular/core';
import { APP_ROUTER_PROVIDERS } from './app.routes';
import {APP_BASE_HREF} from '@angular/common';
bootstrap(AppComponent, [APP_ROUTER_PROVIDERS,provide(APP_BASE_HREF, {useValue : '/' })]);
app.component.ts
app.component.ts
import { Component } from '@angular/core';
import {MenuBarComponent} from "./menubardemo.component";
import {ROUTER_DIRECTIVES} from '@angular/router';
@Component({
selector: 'my-app',
directives: [ROUTER_DIRECTIVES, MenuBarComponent],
template: `
<h1>My First Angular 2 App</h1>
<demo></demo>
<div>
<router-outlet></router-outlet>
</div>
`
})
export class AppComponent { }
new: app.routes.ts
新:app.routes.ts
import {provideRouter,RouterConfig} from '@angular/router';
import {ContentComponent} from './content.component'
export const routes: RouterConfig = [
{path: '', component: ContentComponent}
];
export const APP_ROUTER_PROVIDERS = [
provideRouter(routes)
];
new: content.component.ts (default component)
新:content.component.ts(默认组件)
import { Component } from '@angular/core';
@Component({
selector: 'content',
template: '<div><p>This is some content</p></div>'
})
export class ContentComponent { }
回答by uajov6
i′ve encountered the same problem. I just can't import MenuItem from primeng/primeng, i have even tried to search where is the interface, in fact it is inside the "common" folder, in primeng version 17, the file its called api.d.ts , i tried to copy the interface declaration and use it in my Menu, but for now im just waiting for a solution. Meanwhile you can try this , and it will work, just declare items as any type.
我遇到了同样的问题。我只是无法从 primeng/primeng 导入 MenuItem,我什至试图搜索界面在哪里,实际上它在“common”文件夹内,在primeng 版本 17 中,该文件名为 api.d.ts ,我试图复制接口声明并在我的菜单中使用它,但现在我只是在等待解决方案。同时你可以试试这个,它会起作用,只需将项目声明为任何类型。
private items: any[];
That′s it.
而已。
回答by Ben Gummelt
I just figured this out I believe.
我只是想通了这一点,我相信。
You need to import the MenuModule in the app.module.ts
您需要在 app.module.ts 中导入 MenuModule
//app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
import {MenuModule} from 'primeng/primeng';
import { AppComponent } from './app.component';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
MenuModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
This should fix your problem.
这应该可以解决您的问题。
回答by Ragavan Rajan
May be this will help some one. In my case I forgot to add the libraries in angular.json file
可能这会帮助某人。就我而言,我忘记在 angular.json 文件中添加库
Step 1: In app.module.ts code:
第 1 步:在 app.module.ts 代码中:
@NgModule({
declarations: [AppComponent, HeaderComponent, MenubarComponent],
imports: [
BrowserModule,
BrowserAnimationsModule,
AppRoutingModule,
MenuModule,
MenubarModule,
BreadcrumbModule,
],
?Note: Make sure you have added the Menubar module and import it like below
?注意:确保您已添加 Menubar 模块并将其导入如下
import { MenubarModule } from 'primeng/menubar';
Step 2: If you have menubar in separate component
第 2 步:如果您在单独的组件中有菜单栏
export class MenubarComponent implements OnInit {
items: MenuItem[];
And make sure you have the following import
并确保您有以下导入
import { MenuItem } from 'primeng/api';
Step 3: This was the missingpart for me. If you did the npm installation of primeng then in
第 3 步:这对我来说是缺失的部分。如果你做了primeng的npm安装然后在
In angular.json file: Make sure you have the necessary primeng libraries like below
在 angular.json 文件中:确保你有必要的 Primeng 库,如下所示
under architect build
在建筑师建造下
"styles": [
"node_modules/primeicons/primeicons.css",
"node_modules/primeng/resources/themes/nova-light/theme.css",
"node_modules/primeng/resources/primeng.min.css",
"src/styles.scss"
],
This will display the menubar for sure
这肯定会显示菜单栏
回答by Ha Doan
any errors in browser console? If any, please post it.
浏览器控制台中的任何错误?有的话请发一下。
I think that you need to register p-menubardirective to your component. Try to add directives metadata to @Component.
我认为您需要将p-menubar指令注册到您的组件中。尝试向@Component 添加指令元数据。
@Component({
selector: 'my-app',
template: '<h1>My First Angular 2 App</h1><p-menubar [model]="items"></p-menubar>',
directives: [PMenubar]
})