angular 组件分析及常用内置指令

    技术2026-03-30  18

    一、app.module.ts 组件分析

    1. app.module.ts

    定义 AppModule,这个根模块会告诉 Angular 如何组装该应用。项目中创建的所有组件都会在这里声明。

    2. 自定义组件

    创建组件:

    ng g component components/header

    组件 Module.ts 内容详解:

    import { Component, OnInit } from '@angular/core'; /*引入 angular 核心*/ @Component({ selector: 'app-header', /*使用这个组件的名称*/ templateUrl: './header.component.html', /*html 模板*/ styleUrls: ['./header.component.css'] /*css 样式*/ }) export class HeaderComponent implements OnInit { /*实现接口*/ constructor() { /*构造函数*/ } ngOnInit() { /*初始化加载的生命周期函数*/ } }

    使用组件,

    <app-header></app-header>

    二、angular基本指令

    1、Angular 绑定数据
    数据文本绑定 {{}} <h1> {{title}} </h1> <div> 1+1={{1+1}} </div>

    2.绑定 html

    this.h="<h2>这是一个 h2 用[innerHTML]来解析</h2>" <div [innerHTML]="h"></div>
    2、绑定属性
    <div [id]="id" [title]="msg">调试工具看看我的属性</div>
    3、数据循环 *ngFor

    1、*ngFor 普通循环

    <ul> <li *ngFor="let item of list"> {{item}} </li> </ul>

    2、循环的时候设置 key

    <ul> <li *ngFor="let item of list;let i = index;"> {{item}} --{{i}} </li> </ul>
    4、条件判断 *ngIf
    <p *ngIf="list.length > 3">这是 ngIF 判断是否显示</p> <p template="ngIf list.length > 3">这是 ngIF 判断是否显示</p>
    5、*ngSwitch
    <ul [ngSwitch]="score"> <li *ngSwitchCase="1">已支付</li> <li *ngSwitchCase="2">订单已经确认</li> <li *ngSwitchCase="3">已发货</li> <li *ngSwitchDefault>无效</li> </ul>
    6、执行事件 (click)=”getData()”
    <button class="button" (click)="getData()"> 点击按钮触发事件 </button> <button class="button" (click)="setData()"> 点击按钮设置数据 </button> getData(){ /*自定义方法获取数据*/ //获取 alert(this.msg); } setData(){ //设置值 this.msg='这是设置的值'; }
    7、表单事件
    <input type="text" (keyup)="keyUpFn($event)"/> keyUpFn(e){ console.log(e) }
    8、双向数据绑定

    需要引入:FormsModule

    import { FormsModule } from '@angular/forms'; @NgModule({ declarations: [ AppComponent, HeaderComponent, FooterComponent, NewsComponent ], imports: [ BrowserModule, FormsModule ], providers: [], bootstrap: [AppComponent] }) export class AppModule { }

    使用

    <input type="text" [(ngModel)]="inputValue"/> {{inputValue}}
    9、[ngClass]、[ngStyle]

    [ngClass]:

    <div [ngClass]="{'red': true, 'blue': false}"> 这是一个 div </div> public flag=false; <div [ngClass]="{'red': flag, 'blue': !flag}"> 这是一个 div </div> public arr = [1, 3, 4, 5, 6]; <ul> <li *ngFor="let item of arr, let i = index"> <span [ngClass]="{'red': i==0}">{{item}}</span> </li> </ul>

    [ngStyle]:

    <div [ngStyle]="{'background-color':'green'}">你好 ngStyle</div> public attr='red'; <div [ngStyle]="{'background-color':attr}">你好 ngStyle</div>
    10、管道
    public today=new Date(); <p>{{today | date:'yyyy-MM-dd HH:mm:ss' }}</p>
    Processed: 0.011, SQL: 9