0
点赞
收藏
分享

微信扫一扫

angular知识点梳理第二篇-基本语法

暮晨夜雪 2022-01-20 阅读 47

文章目录

前文回顾

基本语法

常见指令
NgModel
  • 在app.modules.ts中引入forms模块
// 核心模块
import { NgModule } from '@angular/core';
//引入forms模块实现数据的双向绑定
import { FormsModule } from '@angular/forms';
@NgModule({
  declarations: [],
  // 配置当前模块运行所依赖的其他模块
  imports: [FormsModule],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }
  • 在需要使用数据绑定的组件进行数据的处理
import { Component, OnInit} from '@angular/core';
@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.less']
})
export class HomeComponent implements OnInit {
  //声明一个需要绑定的变量
  public inputData:string = ""
  constructor() { }

  ngOnInit(): void {
    console.log("ngOnInit====>")
  } 
}
  • 数据的获取
<h3>angular基本语法梳理</h3>
<!-- [(ngModel)] 是angular的绑定数据的语法 -->
<input [(ngModel)]="inputData" />
<!-- 使用{{}}进行数据的获取 -->
<span>{{inputData}}</span>
  • 运行效果

在这里插入图片描述

NgFor
  • 在需要使用数据绑定的组件进行数据的处理
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.less']
})
export class HomeComponent implements OnInit {
  //声明一个list类型的变量,用于验证NgFor
  public list: Array<any> = [{
    title: '栗子', id: 0
  }, {
    title: '苹果', id: 1
  }, {
    title: '橘子', id: 2
  }, {
    title: '香蕉', id: 3
  }]
  constructor() { }

  ngOnInit(): void {
    console.log("ngOnInit====>")
  }
}
  • 数据视图层获取
<!-- 默认的是没有key的,这里需要key的地方需要给index重新赋值, -->
<ol>
    <li *ngFor="let item of list">{{item.title}}</li>
</ol>
<!-- 将list的索引值获取到赋值给i -->
<ul>
    <li *ngFor="let item of list,let i = index">{{item.title}} - {{i}} - {{item.id}}</li>
</ul>
  • 运行效果
    ngfor运行效果
NgIf
  • 在需要使用数据绑定的组件进行数据的处理
import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-home',
  templateUrl: './home.component.html',
  styleUrls: ['./home.component.less']
})
export class HomeComponent implements OnInit {
  //声明一个boolean类型的变量,用于验证ngif
  public isShow: Boolean = true
  constructor() { }
  ngOnInit(): void {
    console.log("ngOnInit====>")
  }
  /**
   * @function changeIsShow 改变isshow的状态
   */
   changeIsShow() {
    this.isShow = !this.isShow
    console.log("当前isShow:" + this.isShow)
  }
}
  • 数据视图层判断
<br>
<button (click)="changeIsShow()">改变NgIf状态</button>
<br>
<span>当前的isShow:{{isShow}}</span>
<div *ngIf="isShow">我是一个div块</div>
  • 运行效果
  • true显示:
    显示的效果
  • false不显示:
    false不显示
Ng-container
  • 运行效果

在这里插入图片描述

在这里插入图片描述

管道
举报

相关推荐

0 条评论