本篇文章为大家展示了Angular中怎么封装一个并发布组件,内容简明扼要并且容易理解,绝对能使你眼前一亮,通过这篇文章的详细介绍希望你能有所收获。

一、封装组件
目录结构:(部分目录不是框架中自动生成,二是后期添加,按照步骤进行即可。)

具体代码:
html:(search.component.html)
css:(search.component.css)
.form-control{
float: left;
width: 70%;
}
.btn btn-default{
background-color: #41ABE9;
}ts:(search.component.ts)
import {Component, OnInit, Input, Output, EventEmitter} from '@angular/core';
@Component({
selector: 'app-search',
templateUrl: './search.component.html',
styleUrls: ['./search.component.css']
})
export class SearchComponent implements OnInit {
@Input() information: string;
@Input() url: string;
dataUrl: string;
@Output() editData = new EventEmitter();
constructor() { }
ngOnInit() {
}
query(info: string) {
this.dataUrl = this.url + '/' + info;
this.editData.emit(this.dataUrl);
}
} 解释:@Input,接收信息。如information可以接收Html中的{{information}}的值
@Output是输出。即引用组件化的人可以拿到editData的返回值。
module:(search.module.ts)
import {SearchComponent} from './search.component' ;
import {CommonModule} from '@angular/common';
import { NgModule } from '@angular/core';
import { FormsModule } from '@angular/forms';
import { HttpModule } from '@angular/http';
@NgModule({
declarations: [
SearchComponent
],
imports: [
CommonModule,
FormsModule,
HttpModule,
],
providers: [],
exports: [SearchComponent],
})
export class SearchModule { }至此组件完成,可以通过在app.component.html中引入如下看看效果:
{{information}} {{dataUrl}}
对应app.component.ts中需要定义:
import { Component } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent {
information = '输入班级名称';
url= 'Class/find';
dataUrl: string;
query(info: any) {
this.dataUrl = info;
}
}点击查询后效果如:

二、发布,供大家引用
1、注册npm账号:
地址:https://www.npmjs.com
2、手动或者命令创建package.json文件
内容包括:

3、手动或命令创建index.js文件
在添加内容前,我们调整组件的目录结构,如最上图所示,这是规范的目录结构,调整好后,添加index.js内容:
export * from './lib/search.module';
4、手动或命令创建index.d.ts文件
export {SearchModule} from './search.module';5、Ctrl+Shift+右击(在search组件目录下)
运行:npm login
输入账号、密码、邮箱
登录成功后:运行npm publish
至此发布完成。
三、引用者调用:
1、Ctrl+Shift+右击(项目根目录)
cnpm install ng-itoo-search
2、引入到项目中
自己的Module中

3、自己的Html中:
4、对应的ts中:

注意:

上述内容就是Angular中怎么封装一个并发布组件,你们学到知识或技能了吗?如果还想学到更多技能或者丰富自己的知识储备,欢迎关注创新互联成都网站设计公司行业资讯频道。
另外有需要云服务器可以了解下创新互联scvps.cn,海内外云服务器15元起步,三天无理由+7*72小时售后在线,公司持有idc许可证,提供“云服务器、裸金属服务器、高防服务器、香港服务器、美国服务器、虚拟主机、免备案服务器”等云主机租用服务以及企业上云的综合解决方案,具有“安全稳定、简单易用、服务可用性高、性价比高”等特点与优势,专为企业上云打造定制,能够满足用户丰富、多元化的应用场景需求。
文章题目:Angular中怎么封装一个并发布组件-创新互联
文章路径:http://www.jxjierui.cn/article/didijo.html


咨询
建站咨询
