一、封裝組件
作為入門,這是一個非常簡單的demo,但核心的接收使用者的輸入@Input(),以及返回數據給使用者@Output()都實現了,所以有一定的借鑒意義。
目錄結構:(部分目錄不是框架中自動生成,二是后期添加,按照步驟進行即可。)
具體代碼:
html:(search.component.html)
<input type="text" class="form-control" #info placeholder="{{information}}" > <button type="button" class="btn btn-default" (click)="query(info.value);">查詢</button> 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<any>(); 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中引入如下看看效果:
<h1> {{information}} {{dataUrl}} </h1> <div style="width: 300px;padding-left: 5px"> <app-search [information]="information" [url]="url" (editData)="query($event)"></app-search> </div>
對應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賬號:
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中:
<app-search [information]="information" [url]="url " (editData)="query($event)"></app-search>
4、對應的ts中:
注意:
框中的url和ts中保持一致即可,并非必須寫url,自己定義。
OK,現在完整的一個組件就開發、發布完成了。這樣就可以讓其他開發人員引用了。通過這樣的封裝,既可以實現代碼的復用,又會減少項目打包的體積......是Angular的一大優點。
以上就是本文的全部內容,希望對大家的學習有所幫助,也希望大家多多支持武林網。
新聞熱點
疑難解答