官档:https://angular.cn/
安装脚手架
npm install -g @angular/cli
创建项目
ng new 项目名
运行项目
ng serve --open
组件
初始组件位置:
src/app
1.app.component.html/.ts
<h1>hello word</h1>
<!-- 用(click) 绑定点击事件,注意函数名后要带() -->
<button (click)="increment()">自增按钮</button>
<!-- 和vue一样,用{{}}绑定数据 -->
<h2>{{ count }}</h2>
import { Component } from '@angular/core';
//在angular中,组件就是一个类
//@Component 组件的装饰器
@Component({
//用来定义组件渲染的标签名称(组件的名字)
//在index.html 中就有app-root标签
selector: 'app-root',
//用来指定组件的模板文件(写页面标签部分)
templateUrl: './app.component.html',
//用来存放组件相关的样式文件,数组
styleUrls: ['./app.component.scss']
})
//组件类
//vue中,每个组件有自己的data和methods等选项
//这里相当于是组件的data和methods
export class AppComponent {
title = 'angular-demo';
count = 0;
increment = () =>{
//在组件方法中,可以直接使用this访问组件成员
this.count++
}
}
新建组件
用命令新建组件:
ng generate component 组件名
生成的组件文件在src/app/组件名
同时会更新app.module.ts
在组件模板html中:
1.数据绑定:使用{{}}将数据绑定到dom元素,当数据改变时,会影响视图的更新
2.双向数据绑定[(ngModel)]
注意:需要在app.modules.ts中
imports: [
...
FormsModule
],
3.条件渲染
//.component.ts
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-foo',
templateUrl: './foo.component.html',
styleUrls: ['./foo.component.scss']
})
export class FooComponent implements OnInit {
kfc:string = ''
backspaceFn(){
this.kfc = this.kfc.substring(0,this.kfc.length)
}
aaa=true
bbb=false
switchB(){
this.bbb = !this.bbb
}
constructor() { }
ngOnInit(): void {
}
}
//.html
<p>foo works!</p>
<input [(ngModel)]="kfc">
<p>{{ kfc }}</p>
<p *ngIf="aaa">aaa</p>
<p *ngIf="bbb">bbb</p>
<button (click)="switchB()">显示隐藏bbb</button>
4.列表渲染
//.html
<h3 *ngFor="let item of list;let i = index" >
{{i+1}} - {{item.name}}
</h3>
//.component.ts
//列表渲染
list = [
{name:'肯德基'},
{name:'奥利给'},
{name:'突突突'},
]
内联样式[ngStyle]
.html
<div [ngStyle]="currentStyles">
内联样式
</div>
.component.ts
hasBorder:boolean = false
switchBorder(){
this.hasBorder = !this.hasBorder
this.setCurrentStyles()
}
hasBgColor = true;
currentStyles:Record<string,string>={}
setCurrentStyles(){
this.currentStyles = {
'border':this.hasBorder ? 'blue solid 2px' : '',
'background-color': this.hasBgColor ? 'skyblue':'',
}
}
constructor() { }
ngOnInit(): void {
this.setCurrentStyles()
}
组件之间的传值
1.用命令创建父组件 子组件
2