ng 基础
组件的工作只管用户体验,而不用顾及其它。 它应该提供用于数据绑定的属性和方法,以便作为视图和应用逻辑的中介者
组件应该把诸如从服务器获取数据、验证用户输入或直接往控制台中写日志等工作委托给各种服务。通过把各种处理任务定义到可注入的服务类中,你可以让它被任何组件使用
- 插值表达式
- for循环
- 事件和属性绑定
- 双向绑定
- if
- ngSwitch
- 模板引用变量
- 管道
- 属性型指令
- 结构型指令
- ViewChild
- children
- 绑定class
- 绑定style
- 路径别名
- 设置proxy
- ng-container
插值表达式
<div>{{ title }}</div>
<div>{{ !!title ? 1 : 2}}</div>
<div>{{ title() }}</div>
// 变量与字符串的拼接
<li *ngFor="let item of arr" title="{{item}}.txt">{{item}}</li>
<li *ngFor="let item of arr" [title]="item + '.txt'">{{item}}</li>
// 渲染dom标签
<div [innerHTML]="h"></div>
h = `<h2>title</h2>`
for循环
trackByFn 返回唯一id
<li *ngFor="let item of items; index as i; trackBy: trackByFn">...</li>
trackByName(index, it) {
return it.id;
}
arr = ['red', 'blue', 'green'];
<ul *ngFor="let item of arr; index as i; first as f; last as l; even as e; odd as o">
<li [style.color]="item">
item = {{ item }},<br />
index = {{ i }},<br />
Fist? = {{ f }},<br />
Last? = {{ l }},<br />
偶素? = {{ e }},<br />
奇数? = {{ o }}<br />
</li>
</ul>

@Pipe({name: 'demoNumber'})
export class DemoNumber implements PipeTransform {
transform(value, args:string[]) : any {
let res = [];
for (let i = 0; i < value; i++) {
res.push(i);
}
return res;
}
}
<ul>
<li>Method First Using PIPE</li>
<li *ngFor='let key of 5 | demoNumber'>
{{key}}
</li>
</ul>
硬编码
<ul>
<li>Method Second</li>
<li *ngFor='let key of [1,2]'>
{{key}}
</li>
</ul>
事件和属性绑定
<button (click)="alert()" [title]="title">click</button>
双向绑定
import { FormsModule } from '@angular/forms';
@NgModule({
imports: [FormsModule] // 需要这个模块,通常在shared模块中导出
})
<input type="text" name="name" [(ngModel)]="name" /> {{ name }}
展开双向绑定
<input type="text" name="name" [(ngModel)]="name" (ngModelChange)="nameChange($event)"/> {{ name }}
name = "ajanuw";
nameChange(v: string) {
this.name = v.toLocaleUpperCase();
}
if
myName = '';
ngOnInit() {
setTimeout(() => this.myName = 'alone', 2000);
}
<p *ngIf="myName; else elesTemp" >{{ myName }}</p>
<ng-template #elesTemp>
<p> 暂无数据!</p>
</ng-template>
if/then/else
<p *ngIf="myName; then thenTemp; else elesTemp"></p>
<ng-template #thenTemp>
<p>{{ myName }}</p>
</ng-template>
<ng-template #elesTemp>
<p> 暂无数据!</p>
</ng-template>
ngSwitch
<div [ngSwitch]="name">
<p *ngSwitchCase="'ajanuw'">hello {{name}}</p>
<p *ngSwitchCase="'coo'">bey bey {{name}}</p>
<p *ngSwitchCase="'boo'">i'm {{name}}...</p>
<p *ngSwitchDefault>not name!</p>
</div>
模板引用变量
<div>{{ name.name }}_{{ name.value }}</div>
<input type="text" name="name" value="123" #name />
<button (click)="onClick(name.value)">click me</button>
onClick(v: string) {
l(v); // 123
}
// 获取组件实例(只能在模板中调用),类似react使用ref获取组件实例
<app-hello #hello></app-hello>
<button (click)="hello.event()">click me</button>
管道
<p>{{ 'ajanuw' | uppercase }}</p> 全大写 -> AJANUW
<p>{{ 'Ajanuw' | lowercase }}</p> 全小写 -> ajanuw
<p>{{ 'hi ajanuw' | titlecase }}</p> 单词首写大写 -> Hi Ajanuw
<p>{{ {name: 'ajanuw'} | json }}</p> onj => json
<p>{{ 'ajanuw' | slice:1:3 }}</p> 类似js的slice -> ja
处理number
<p>{{ 3.141 | number:'1.2-2' }}</p> -> 3.14
<p>{{ 3.141 | number:'1.1-3' }}</p> -> 3.141
<p>{{ 3.141 | number:'2.1-1' }}</p> -> 03.1
<p>{{ 3.141 | number:'2.4-4' }}</p> -> 03.1410
<p>{{ 0.5 | percent }}</p> 百分比 -> 50%
<p>美元: {{ 5 | currency }}</p> 这两个都没什么卵用
<p>英镑:{{ 5 | currency:'GBP' }}</p>
- 创建
ng g @schematics/angular:pipe mathCeil --project=angular-universal --module=app.module.ts --no-spec
- 使用
<div>{{ 12.3 | mathCeil: 2 }}</div>
- 实现
import { Pipe, PipeTransform } from "@angular/core";
@Pipe({
name: "mathCeil",
})
export class MathCeilPipe implements PipeTransform {
/**
* @param value 传入的值
* @param args 传入的参数
*/
transform(value: number, args?: number): any {
console.log(args); // 2
return Math.ceil(value);
}
}
父子组件传递参数 组件之间的交互
<app-hello [name]="name" (onAlert)="onAlert($event)"></app-hello>
name = "ajanuw";
onAlert(v: string) {
l(v);
}
Input输入, Output 输出
<h2 (click)="handleClick()">{{name}}</h2>
@Input() name: string;
@Output() onAlert = new EventEmitter<string>();
handleClick() {
this.onAlert.emit("hello...");
}
属性型指令
- 创建指令
ng g directive highlight
- 使用
<h1 [appHighlight]="'blue'" [defaultColor]="'#f48'">Welcome to {{ title }}!</h1>
- 实现
import { Directive, ElementRef, HostListener, Input } from "@angular/core";
const l = console.log;
@Directive({
selector: "[appHighlight]",
})
export class HighlightDirective {
@Input("appHighlight")
public color: string; // 设置选中时的颜色
// 初始化时的颜色
@Input()
public set defaultColor(color: string) {
this.setColor(color);
}
// el: 获取指令绑定的dom元素
constructor(private readonly el: ElementRef) {}
// 响应用户引发的事件
@HostListener("mouseenter")
public onMouseEnter(): void {
this.setColor(this.color || "red");
}
@HostListener("mouseleave")
public onMouseLeave(): void {
this.setColor(null);
}
private setColor(color: string): void {
this.el.nativeElement.style["color"] = color;
}
}
结构型指令
- 创建指令
ng g @schematics/angular:directive delay --project=angular-universal --module=app.module.ts --no-spec
- 使用
<div *appDelay="1200">
hello <ng-container *ngIf="!!username"> {{ username }} </ng-container>
</div>
- 实现
delay.directive.ts
import {
Directive,
Input,
TemplateRef,
ViewContainerRef,
OnDestroy,
} from "@angular/core";
@Directive({
selector: "[appDelay]",
})
export class DelayDirective implements OnDestroy {
private timer: NodeJS.Timer;
constructor(
private readonly templateRef: TemplateRef<any>,
private readonly viewContainer: ViewContainerRef,
) {}
// 延迟加载dom
@Input()
public set appDelay(delayNum: number) {
this.timer = setTimeout(() => {
this.viewContainer.createEmbeddedView(this.templateRef);
}, delayNum);
}
ngOnDestroy(): void {
clearTimeout(this.timer);
}
}
ViewChild
获取子组件的实例,和dom节点
<app-hello></app-hello>
<button (click)="onClick()">click me</button>
import { Component, OnInit, AfterViewInit, ViewChild } from "@angular/core";
import { HelloComponent } from "./hello/hello.component";
export class AppComponent implements OnInit, AfterViewInit {
@ViewChild(HelloComponent)
private helloRef: HelloComponent; // 注入HelloComponent实例到helloRef
ngOnInit(): void {}
// 组件的视图初始化之后
ngAfterViewInit() {
this.helloRef.handleOk(); // 调用HelloComponent实例的方法
}
onClick() {
this.helloRef.handleOk();
}
}
获取dom节点
<div #test>hello</div>
@ViewChild("test") public testRef: ElementRef;
ngAfterViewInit(): void {
console.log(this.testRef.nativeElement.textContent); // hello
}
children
ng-content 获取所有children,用select获取指定children,不能重复获取
<app-hello>
<h2>hello</h2>
<footer>footer</footer>
</app-hello>
// app-hello 获取children
<div class="a">
<ng-content select='footer'></ng-content>
<ng-content select='h2'></ng-content>
</div>
? ! $any()
The current hero's name is {{currentHero?.name}} // 安全返回
<div *ngIf="hero">
The hero's name is {{hero!.name}} // 非空断言操作符
</div>
Undeclared members is {{$any(this).member}} // 使用 $any 转换函数来把表达式转换成 any 类型
绑定class
classes = {
'text-danger': true,
'text-success': false,
'p-2': true
};
<p class="a" [class]="'text-danger'">{{ txt() }}</p> // 'text-danger'
<p class="a" [class.text-danger]="true">{{ txt() }}</p> // 'a text-danger'
<p class="a" [ngClass]="classes">{{ txt() }}</p> // 'a text-danger p-2'
绑定style
styles = {
color: 'red',
padding: '1rem',
backgroundColor: '#e5e5ef75',
display: 'inline-block'
};
<p style="font-family: Consolas;" [style.color]="'red'">{{ txt() }}</p>
<p style="font-family: Consolas;" [ngStyle]="styles">{{ txt() }}</p>
设置proxy
proxy.conf.json
{
"/api": {
"target": "http://localhost:5000",
"secure": false,
"pathRewrite": {
"^/api": ""
}
}
}
ngOnInit() {
this.msg$ = this.http.get("/api/ng7", {
responseType: "text",
});
}
ng-container
用来挂载结构型指令, 避免使用多余的 html 元素挂载指令
<div>
hello <ng-container *ngIf="!!username"> {{ username }} </ng-container>
</div>
<div>
hello <span *ngIf="!!username"> {{ username }} </span>
</div>
按键事件
<input #box (keyup.enter)="onEnter(box.value); box.value=''">
ng 基础的更多相关文章
- AngularJS 1.2.x 学习笔记(表单校验篇)
https://my.oschina.net/cokolin/blog/526911 摘要: 本文首发于 blog.csdn.net/vipshop_ebs/article/details/39472 ...
- Angular CLI命令
ng 基础命令 npm install –g @angular/cli npm install -g @angular/cli@latest ng serve –prot –aot 启动项目并压缩项目 ...
- Nginx导航
简介 最近都在弄微服务的东西,现在来记录下收获.我从一知半解到现在能从0搭建使用最大的感触有两点 1.微服务各大组件的版本很多,网上很多博客内容不一定适合你的版本,很多时候苦苦琢磨都是无用功 2.网上 ...
- matlab基础教程——根据Andrew Ng的machine learning整理
matlab基础教程--根据Andrew Ng的machine learning整理 基本运算 算数运算 逻辑运算 格式化输出 小数位全局修改 向量和矩阵运算 矩阵操作 申明一个矩阵或向量 快速建立一 ...
- ng机器学习视频笔记(一)——线性回归、代价函数、梯度下降基础
ng机器学习视频笔记(一) --线性回归.代价函数.梯度下降基础 (转载请附上本文链接--linhxx) 一.线性回归 线性回归是监督学习中的重要算法,其主要目的在于用一个函数表示一组数据,其中横轴是 ...
- Andrew Ng - 深度学习工程师 - Part 1. 神经网络和深度学习(Week 2. 神经网络基础)
=================第2周 神经网络基础=============== ===2.1 二分分类=== ===2.2 logistic 回归=== It turns out, whe ...
- angular学习的一些小笔记(中)之基础ng指令
一.布尔属性指令: ng-disabled:就是ng-disabled=true-->就指向不可用 <!doctype html> <html ng-app="&qu ...
- 写在读ng之前的基础知识----笔记
如果要看angular的代码, 先把这个给看了, 司徒的干货. /******************************************************************* ...
- 【Machine Learning】机器学习及其基础概念简介
机器学习及其基础概念简介 作者:白宁超 2016年12月23日21:24:51 摘要:随着机器学习和深度学习的热潮,各种图书层出不穷.然而多数是基础理论知识介绍,缺乏实现的深入理解.本系列文章是作者结 ...
随机推荐
- 高性能缓存 Caffeine 原理及实战
一.简介 Caffeine 是基于Java 8 开发的.提供了近乎最佳命中率的高性能本地缓存组件,Spring5 开始不再支持 Guava Cache,改为使用 Caffeine. 下面是 Caffe ...
- Linux常用命令详解(第三章)(ping、kill、seq、du、df、free、date、tar)
本章命令(共7个): 1 2 3 4 5 6 7 8 ping kill seq du df free date tar 1." ping " 作用:向网络主机发送ICMP(检测主 ...
- [OpenCV]获取摄像头视频
环境:Windows 8 64bit + VS2012 X64 + OpenCV 2.4.7 摄像头的捕捉使用VideoCapture类 Class VideoCapture [OpenCV文档 ...
- CF1313C2 Skyscrapers (hard version)
思路: 使用单调栈. 实现: 1 #include <bits/stdc++.h> 2 using namespace std; 3 typedef long long ll; 4 con ...
- 【noi 2.6_9267】核电站(DP)
题意:n个数中不能同时选连续m个或以上,问方案数. 解法:f[i][j]表示从前i个中选,到第i个已经连续选了j个.j!=0时, =f[i-1][j-1] ; j=0时, =f[i-1][0~m-1 ...
- hdu3706 Second My Problem First
Problem Description Give you three integers n, A and B. Then we define Si = Ai mod B and Ti = Min{ ...
- Codeforces Round #641 div2 B. Orac and Models (DP)
题意:有一个长度为\(n\)的序列\(a\),求一个最长上升子序列,且这个子序列的元素在\(a\)中的位置满足\(i_{j+1}modi_{j}=0\),求这个子序列的最大长度. 题意:这题假如我们用 ...
- Dapr微服务应用开发系列3:服务调用构件块
题记:这篇开始逐一深入介绍各个构件块,从服务调用开始 原理 所谓服务调用,就是通过这个构件块让你方便的通过HTTP或者gRPC协议同步调用其他服务的方法,这些方法也是通过HTTP或者gRPC来暴露的. ...
- k8s二进制部署 - node节点安装
创建kubelet配置 • set-cluster # 创建需要连接的集群信息,可以创建多个k8s集群信息 [root@hdss7-21 ~]# kubectl config set-cluster ...
- k8s二进制部署 - etcd节点安装
下载etcd [root@hdss7-12 ~]# useradd -s /sbin/nologin -M etcd [root@hdss7-12 ~]# cd /opt/src/ [root@hds ...