Angular

官档: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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值