内容简介:1.创建项目;1.打开项目2.创建commponent
1.创建项目;
- 全局安装angular
npm install -g @angular/cli 复制代码
- 新建项目
ng new angular-tour-of-heroes; cd angular-tour-of-heroes //然后输入命令 查看angular版本信息: ng --version 复制代码
- 开始(监听)项目 (这个命令以后会常用):
ng serve --open;
//恭喜你,现在你已经可以输出自己的“hello,world”了。
复制代码
2.常用命令
1.打开项目
ng serve --open 复制代码
2.创建commponent
ng generate component componentName 复制代码
3.创建service
ng generate service servicenName --module=app 复制代码
4.创建路由
ng generate module app-routing --flat --module=app 复制代码
5.启动或开始
ng serve --open
ng serve --port 0 --open
复制代码
6.发布
ng build --prod --base-href ../GBmono/ 复制代码
3.angular组件
| Scaffold | Usage |
|---|---|
| Component | ng g component my-new-componen - 指定目录创建 components/Footer |
| Directive | ng g directive my-new-directive |
| Pipe | ng g pipe my-new-pipe |
| Service | ng g service my-new-service |
| class | ng g class my-new-class |
| Guard | ng g guard my-new-guard |
| Interface | ng g interface my-new-interface |
| Enum | ng g enum my-new-enum |
| Module | ng g module my-module |
1.创建组件
1.1 ng g component components/header 1.2使用组件
<app-header></app-header> 复制代码
1.3 数据文本绑定
<h1>
{{title}}
</h1>
复制代码
2.绑定 html
this.h="<h2>这是一个 h2 用[innerHTML]来解析</h2>" <div [innerHTML]="h"></div> 复制代码
3.数据循环*ngFor
<ul>
<li *ngFor="let item of list">
{{item}}
</li>
</ul>
<!-- 循环时设置key -->
<ul>
<li *ngFor="let item of list;let i = index;">
{{item}} --{{i}}
</li>
</ul>
复制代码
4.条件判断*ngIf
<p *ngIf="list.length > 3">这是 ngIF 判断是否显示</p> <p template="ngIf list.length > 3">这是 ngIF 判断是否显示</p> 复制代码
5.执行事件 (click)="getData()"
<button class="button" (click)="getData()"> 点击按钮触发事件 </button> <button class="button" (click)="setData()"> 点击按钮设置数据 </button> 复制代码
getData(){ /*自定义方法获取数据*/
//获取
alert(this.msg);
}
setData(){
//设置值
this.msg='这是设置的值';
}
复制代码
6.绑定属性
<div [id]="id" [title]="msg">调试 工具 看看我的属性</div> 复制代码
keyUpFn(e){
console.log(e)
}
复制代码
7.双向数据绑定
<input [(ngModel)]="inputValue"> 复制代码
7.1.引入FormsModule;
import { FormsModule } from '@angular/forms';
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
FooterComponent,
NewsComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
复制代码
8.Todolist 功能
<input type="text" [(ngModel)]='username'>
<button (click)='addData()'>增加</button>
<ul>
<li *ngFor="let item of list">
{{item}}
</li>
</ul>
复制代码
export class TodolistComponent implements OnInit {
list:any[];
username:any;
constructor() {}
ngOnInit() {
this.list=[];
this.username='';
}
addData(){
alert(this.username);
this.list.push(this.username);
}
}
复制代码
4.父组件给子组件传值 - @Input
1.父组件调用子组件的时候传入数据
<app-header [msg]="msg"></app-header> 复制代码
2.子组件引入 Input 模块
import { Component, OnInit ,Input } from '@angular/core';
复制代码
3.子组件中 @Input 接收父组件传过来的数据
export class HeaderComponent implements OnInit {
@Input() msg:string
constructor() { }
ngOnInit() {
}
}
复制代码
4.子组件中使用父组件的数据
<h2>这是头部组件--{{msg}}</h2>
复制代码
5.父子组件传值的方式让子组件执行父组件的方法5.1父组件定义方法
run(){
alert("我是父组件方法!")
}
复制代码
5.2调用子组件传入当前方法
<app-header [msg]="msg" [run]="run"></app-header> 复制代码
5.3. 子组件接收父组件传过来的方法
import { Component, OnInit ,Input } from '@angular/core';
export class HeaderComponent implements OnInit {
@Input() msg:string
@Input() run:any;
constructor() { }
}
复制代码
5.4. 子组件使用父组件的方法。
export class HeaderComponent implements OnInit {
@Input() msg:string;
@Input() run:any;
constructor() { }
ngOnInit() {
this.run(); /*子组件调用父组件的 run 方法*/
}
}
复制代码
6.子组件通过@Output执行父组件的方法6.1 子组件引入 Output 和 EventEmitter
import { Component, OnInit ,Input,Output,EventEmitter} from '@angular/core';
复制代码
6.2 子组件中实例化 EventEmitter
@Output() private outer=new EventEmitter<string>(); 复制代码
6.3 子组件通过 EventEmitter 对象 outer 实例广播数据
sendParent(){
// alert('zhixing');
this.outer.emit('msg from child')
}
复制代码
6.4 父组件调用子组件的时候,定义接收事件 , outer 就是子组件的 EventEmitter 对象 outer
<app-header (outer)="runParent($event)"></app-header> 复制代码
6.5 父组件接收到数据会调用自己的 runParent 方法,这个时候就能拿到子组件的数据
//接收子组件传递过来的数据
runParent(msg:string){
alert(msg);
}
复制代码
7.父组件通过局部变量获取子组件的引用,主动获取子组件的数据和方法(一)
7.1定义 footer 组件
export class FooterComponent implements OnInit {
public msg:string;
constructor() {
}
ngOnInit() {
}
footerRun(){
alert('这是 footer 子组件的 Run 方法');
}
}
复制代码
7.2.父组件调用子组件的时候给子组件起个名字
<app-footer #footer></app-footer> 复制代码
7.3.直接获取执行子组件的方法
<button (click)='footer.footerRun()'>获取子组件的数据</button> 复制代码
8.父组件通过局部变量获取子组件的引用,通过 ViewChild主动获取子组件的数据和方法8.1.调用子组件给子组件定义一个名称
<app-footer #footerChild></app-footer> 复制代码
8.2 引入 ViewChild
import { Component, OnInit ,ViewChild} from '@angular/core';
复制代码
8.3.ViewChild 和刚才的子组件关联起来
@ViewChild('footerChild') footer;
复制代码
8.4.调用子组件
run(){
this.footer.footerRun();
}
复制代码
5.路由
1.创建一个简单路由;
- Add the AppRoutingModule
ng generate module app-routing --flat --module=app; 复制代码
app-routing
import { RouterModule, Routes } from '@angular/router';
import { MyCompComponent } from './my-comp/my-comp.component';
import { SiginComponent } from './sigin/sigin.component';
import { HomeModuleComponent } from './home-module/home-module.component';
const appRoutes: Routes = [
{
path: '',
redirectTo: '/sigin',
pathMatch: 'full'// 针对控的path 必须指定full;
},
{
path: 'sigin',
component: SiginComponent,
},
{
path: 'index',
component: MyCompComponent,
},
{
path: 'home',
component: HomeModuleComponent,
}
];
@NgModule({
declarations: [],
imports: [
CommonModule,
RouterModule.forRoot(appRoutes)
],
exports: [RouterModule]
})
export class AppRoutingModule { }
复制代码
2.所有在组建中使用的路由必须在app.module中注册使用;
app.module.ts
import { MyCompComponent } from './my-comp/my-comp.component';
import { HomeModuleComponent } from './home-module/home-module.component';
import { SiginComponent } from './sigin/sigin.component';
@NgModule({
declarations: [
AppComponent,
SiginComponent,
MyCompComponent,
HomeModuleComponent
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
HttpClientModule,
NgZorroAntdModule,
ReactiveFormsModule
],
providers: [{ provide: NZ_I18N, useValue: zh_CN }],
bootstrap: [AppComponent]
})
复制代码
3.路由默认选中路由
- Angular routerLinkActive 设置 routerLink 默认选中路由
<h1>
<a routerLink="/home" routerLinkActive="active">首页</a>
<a routerLink="/news" routerLinkActive="active">新闻</a>
</h1>
<style>
.active{
color:red;
}
<style>
复制代码
4.动态路由使用;
app-routing.module.ts
const routes: Routes = [
{
path: 'home',
component:HomeComponent
},
{
path: 'news',
component:NewsComponent
},
{
path: 'newscontent/:aid', /*配置动态路由*/
component:NewscontentComponent
}
,{ /*匹配不到路由的时候加载的组件*/
path: '**', /*任意的路由*/
// component:HomeComponent
redirectTo:'home'
}
];
复制代码
newscontent.component.ts
ngOnInit() {
//获取动态路由
// console.log(this.route.params.value.aid); //错误的写法
//获取动态路由的传值
this.route.params.subscribe(function(data){
console.log(data.aid);
})
}
复制代码
5.路由的js跳转 5.1.引入
import { Router } from '@angular/router';
复制代码
5.2.初始化
export class HomeComponent implements OnInit {
constructor(private router: Router) {
}
ngOnInit() {
}
goNews(){
// this.router.navigate(['/news', hero.id]);
this.router.navigate(['/news']);
}
}
复制代码
5.3.路由跳转 5.4普通跳转
this.router.navigate(['/news', hero.id]); 复制代码
5.5 路由的js跳转get传值;
//引入 NavigationExtras
import { Router ,NavigationExtras,ActivatedRoute} from '@angular/router';
//定义一个 goNewsContent 方法执行跳转, 用 NavigationExtras 配置传参
goNewsContent(){
let navigationExtras: NavigationExtras = {
queryParams: { 'session_id': '123' },
fragment: 'anchor'
};
this.router.navigate(['/news'],navigationExtras);
}
//获取 get 传值
constructor(private route: ActivatedRoute) {
console.log(this.route.queryParams);
}
复制代码
6.父子路由 6.1.创建组件引入组件
import { NewsaddComponent } from './components/newsadd/newsadd.component';
import { NewslistComponent } from './components/newslist/newslist.component';
复制代码
6.2.配置路由
{
path: 'news',
component:NewsComponent,
children: [
{
path:'newslist',
component:NewslistComponent
},
{
path:'newsadd',
component:NewsaddComponent
}
]
}
复制代码
6.3.父组件中定义 router-outlet
<router-outlet></router-outlet> 复制代码
6.服务(service)
6.1安装
ng g service my-new-service //创建到指定目录下面 ng g service services/storage 复制代码
- app.module.ts 里面引入创建的服务
//1.app.module.ts 里面引入创建的服务
import { StorageService } from './services/storage.service';
//2. NgModule 里面的 providers 里面依赖注入服务
@NgModule({
declarations: [
AppComponent,
HeaderComponent,
FooterComponent,
NewsComponent,
TodolistComponent
],
imports: [
BrowserModule,
FormsModule
],
providers: [StorageService],
bootstrap: [AppComponent]
})
export class AppModule { }
复制代码
- 使用的页面引入服务,注册服务
//引入服务
import { StorageService } from '../../services/storage.service';
//constuctor
constructor(private storage: StorageService) { };
//使用
addData(){
// alert(this.username);
this.list.push(this.username);
this.storage.set('todolist',this.list);
}
removerData(key){
console.log(key);
this.list.splice(key,1);
this.storage.set('todolist',this.list);
}
复制代码
6.2.使用 6.2.1.引入 HttpModule、JsonpModule 普通的 HTTP 调用并不需要用到 JsonpModule,不过稍后我们就会演示对 JSONP 的支持, 所以现在就加载它,免得再回来改浪费时间
import { HttpModule, JsonpModule } from '@angular/http';
复制代码
6.2.2.HttpModule 、 JsonpModule依赖注入
@NgModule({
declarations: [
AppComponent,
HomeComponent,
NewsComponent,
NewscontentComponent
],
imports: [
BrowserModule,
FormsModule,
HttpModule,
JsonpModule,
AppRoutingModule
],
providers: [StorageService,NewsService],
bootstrap: [AppComponent]
})
export class AppModule { }
复制代码
6.2.3.app.module.ts 引入并且依赖注入完成以后, 在需要用到的地方执行下面操作 6.3.使用 Http、 Jsonp: 6.3.1.在需要请求数据的地方引入 Http
import {Http,Jsonp} from "@angular/http";
复制代码
6.3.2、 构造函数内申明:
constructor(private http:Http,private jsonp:Jsonp) { }
复制代码
6.3.3、对应的方法内使用 http 请求数据
//get
this.http.get("http://www.phonegap100.com/appapi.php?a=getPortalList&ca
tid=20&page=1")
.subscribe(
function(data){
console.log(data);
},function(err){
console.log('失败');
}
);
//jsonp
this.jsonp.get("http://www.phonegap100.com/appapi.php?a=getPortalList&catid=20&page=1&callback=JSONP_CALLBACK")
.subscribe(
function(data){
console.log(data);
},function(err){
console.log('失败');
}
);
复制代码
6.4.使用 Post; 6.4.1 引入 Headers 、 Http 模块
import {Http,Jsonp,Headers} from "@angular/http";
复制代码
6.4.2 实例化 Headers
private headers = new Headers({'Content-Type': 'application/json'});
复制代码
6.4.3.post 提交数据
this.http
.post('http://localhost:8008/api/test',
JSON.stringify({username: 'admin'}), {headers:this.headers})
// .toPromise()
.subscribe(function(res){
console.log(res.json());
});
复制代码
以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持 码农网
猜你喜欢:本站部分资源来源于网络,本站转载出于传递更多信息之目的,版权归原作者或者来源机构所有,如转载稿涉及版权问题,请联系我们。
群智能优化算法及其应用
雷秀娟 / 2012-8 / 85.00元
《群智能优化算法及其应用》编著者雷秀娟。 《群智能优化算法及其应用》内容提要:本书以群智能优化算法中的粒子群优化(]Particle Swarm Optimization,PSO)算法为主线,着重阐述了PSO算法的基本原理、改进策略,从解空间设计、粒子编码以及求解流程等方面进行了详细设计与阐述,对蚁群优化(Ant Colony Optimization,AC0)算法、人工鱼群(Art......一起来看看 《群智能优化算法及其应用》 这本书的介绍吧!