angular9.x基本使用

894 阅读2分钟

一、环境搭建以及创建项目

1.1前提条件

nodejs>=10.9.0 和 npm包管理器

1.2安装cnpm

//使用淘宝镜像,也可以换成其他的
npm install -g cnpm --registry=https://registry.npm.taobao.org

1.3安装angular-cli

//全局安装
cnpm install -g @angular/cli

//检查是否安装成功
ng v

1.4创建项目

// 直接创建
ng new ngdemo

//跳过自动安装依赖包,直接安装有时候会出错
ng new ngdemo --skip-install
cnpm install

1.5启动项目

cd ngdemo
ng serve 或者 npm run start
// 自动打开浏览器并访问项目地址
ng serve --open

二、基本用法

2.1 创建一个组件

ng generate component 组件名(generate简写g,component简写c )
默认在app根目录下生成

ng g c heroes

heroes组件有四个文件:

  • .spec.ts是测试文件,不用管,。
  • .component.css里面写该组件的样式
  • .component.html里面写html标签,
  • .component.ts里面写属性方法等处理逻辑

2.2 使用组件

    <app-heroes></app-heroes>

组件名就是装饰器中的selector

2.3 常用语法

2.3.1 插值 {{}}

{{hero.name}}

插值会把属性的值作为文本渲染出来

2.3.2 循环 *ngFor

<li *ngFor="let hero of heroes">
  {{hero.name}}
</li>

2.3.3 条件判断 *ngIf

<div *ngIf="heroes.length"></div>

如果heroes为空,不显示

2.3.4 动态属性绑定 []

<li *ngFor="let hero of heroes" [title]="hero.name">
  {{hero.name}}
</li>

若属性值静态的,属性就不需要用[]括起来

2.3.5 事件绑定 ()

<button (click)="delete()">x</button>

方法后面一定要带(),不然方法不执行

2.3.6 双向绑定 [(ngModel)]

<input [(ngModel)]="inputVal">

2.3.7 样式

<div [ngStyle]="{'background-color':'red'}">style</div>
<div [ngClass]="{'active': true}">class</div>

2.3.8 管道

内置管道

<p>{{ 'semlinker'| uppercase }}</p> 
<p>{{ 'SEmlinker'| lowercase }}</p> 

自定义管道

//1 生成管道文件 common.pipe.ts
ng g pipe common
//2 common.pipe.ts 中定义多个管道
import { Pipe, PipeTransform } from '@angular/core';
@Pipe({
  name: 'common1'
})
export class CommonPipe implements PipeTransform {
  transform(value: any): any {
    return `${value}人`
  }
}

@Pipe({
  name: 'common2'
})
export class CommonPipe2 implements PipeTransform {
  transform(value: any): any {
    return value+1
  }
}

//3 app.module.ts 中引入
import { CommonPipe, CommonPipe2 } from './common.pipe';
...
@NgModule({
  declarations: [
    ...
    CommonPipe,
    CommonPipe2
  ]
  ...
}

//4 页面中使用
<div>{{age|common1}}</div>
<div>{{age|common2}}</div>

2.3.9 传值-父传子

父组件

//父组件 demo.component.html 中
<app-demo1 [product]="product"></app-demo1>

//父组件 demo.component.ts 中
export class DemoComponent implements OnInit {
  public product = 'xxx'
  ...
}

子组件

//demo1.component.ts中
import { Input } from '@angular/core';
export class Demo1Component implements OnInit {
    @Input() product
    ...
}

//demo1.component.html 中
<div>{{product}}</div>

2.3.10 传值-子传父

子组件

//demo1.component.ts 中
import { Output, EventEmitter } from '@angular/core';
export class Demo1Component implements OnInit {
    @Output() notifyEvent = new EventEmitter()
}

//demo1.component.html 中
<div (click)="notifyEvent.emit()">notify</div>

父组件

//demo.component.html中
<div (notifyEvent)="alert(1)"></div>