Angular - 笔记

文章目录

语法

属性绑定

Angular 的双向绑定语法是方括号和圆括号的组合 [()][] 进行属性绑定,() 进行事件绑定。

ts 复制代码
1. 语法
// 在属性上用{{}}
<p title="{{title}}">

// 使用[]做属性绑定 
<p [title]="title">
    
举例:
//html文件
    <p>属性绑定</p>
    <div [id]="'apple'">Apple</div>
    <div [id]="lemon">{{lemon}}</div>
    <div id="{{lemon}}">{{lemon}}</div>
    
    <div [class]="'item'">绑定Class - 1</div>
    <div [class]="itemClass">绑定Class - 2</div>

    <h3 [class.h3-dom]="h3Dome">class.h3-dom根据true决定是否显示</h3>
    <h3 [class.h3-dom]="'true'">class.h3-dom根据true决定是否显示</h3>  // 也可以渲染成功

    <h3 [class]="'h3-dom font w string'">多类名绑定</h3>
    <a [title]="product.name + ' details'">  {{ product.name }} </a>

// ts文件
  lemon : string = 'lemon'
  itemClass : string ='item-Class';
  h3Dome : boolean = true;
  product = {name: '张三'};
  1. ngMoudle
ts 复制代码
// home.html eg: 1 - 使用 ngModel 作为键,把该指令导出到一个局部模板变量中(如:#myVar="ngModel")
    <input [(ngModel)]="name" #ctrl="ngModel" required>

    <p>Value: {{ name }}</p>  <!--111-->
    <p>Value: {{ ctrl.value }}</p> <!--111-->
    <p>Valid: {{ ctrl.valid }}</p> <!--true-->
// home.html eg: 2
    <label for="example-ngModel">[(ngModel)]:</label>
    <input [(ngModel)]="currentItem.name" id="example-ngModel"> 
// home.ts
    export class HomePage {
      currentItem = {name: '张三'};
    }
// home.html   eg: 3 - ngForm中使用 ngModel
    <div>
        <form #f="ngForm" (ngSubmit)="onSubmit(f)" novalidate>
            <input name="first" ngModel required #first="ngModel">
            <br>
            <input name="last" ngModel>
            <br>
            <button>Submit</button>
        </form>

        <p>First name value: {{ first.value }}</p>
        <p>First name valid: {{ first.valid }}</p>
        <p>Form value: {{ f.value | json }}</p>
        <p>Form valid: {{ f.valid }}</p>
    </div>

引用模板变量

  1. 语法:在模板中,要使用井号 # 来声明一个模板变量。下列模板变量 #phone 声明了一个名为 phone 的变量,其值为此 <input> 元素。
ts 复制代码
<input #phone placeholder="phone number" />

<!--可以在组件模板中的任何地方引用某个模板变量。这里的 <button> 就引用了 phone 变量-->
utton type="button" (click)="callPhone(phone.value)">Call</button>

// eg:1 这个是input自带value属性,{{phone.value}}会呈现test,更改input值不会有改变,因为没写ngMoudle进行双向绑定
<input #phone placeholder="phone number" value="text" />
<p>Value: {{ phone.value }}</p>

// eg:2 双向数据绑定
<input #phone type="text" id="name" class="form-control" name="name" ngModel required />
{{phone.value}}

组件绑定

父组件传子组件 @input

现在有父组件<parentlist> 和子组件<childlist>

  1. 配置子组件
ts 复制代码
//userlist.ts
import { Component, Input } from '@angular/core'; // First, import Input
export class ChildComponent {
  @Input() item = ''; // decorate the property with @Input()
}
// userlist.html
Userlist组件:Today's item: {{item}}
  1. 配置父组件
ts 复制代码
//parentlist.ts
export class ParentComponent { // 业务逻辑
  currentItem = 'Television';
}
// parentlist.html
<parentlist [item]="currentItem"></parentlist>

运行结果如下,这样就实现了父组件的 currentItem 变量绑定给了子组件的 item

子组件传父组件 @output
  1. 子组件
ts 复制代码
// 1. html 
    <label for="item-input">Add an item:</label>
    <input type="text" id="item-input" #newItem>
    <button ion-button  (click)="addNewItem(newItem.value)">Add</button>

// 2. ts
import { Output, EventEmitter } from '@angular/core';

export class ChildComponent {
  @Output() newItemEvent = new EventEmitter<string>();
  
  addNewItem(value: string) {
    // value = "测试value";
    this.newItemEvent.emit(value);
    console.log("----"+value);
  }
}
  1. 父组件
ts 复制代码
// 1. html
    <child (newItemEvent)="addItem($event)"></child>
    <ul>
        <li *ngFor="let item of items">{{item}}</li>
    </ul>

// 2. ts
export class ParentComponent {
  items = ['item1', 'item2', 'item3', 'item4'];
  
  addItem(newItem: string) {
    this.items.push(newItem);
    console.log(newItem);
  }
}

上述可以这么理解:

  1. 当触发子组件的 addNewItem() 函数时,页面数据双向绑定去拿到一个值给到 newItemEvent
  2. 父组件根据 @outpiy newItemEvent 拿到的值,即作为参数 event ,去执行 addItem 函数给到 items ,然后页面输出。
EventEmitter

Angular 提供了一个 EventEmitter 类,它用来通过组件的 @Output() 装饰器 发送一些值。EventEmitter 扩展了 RxJS Subject,并添加了一个 emit() 方法,这样它就可以发送任意值了。当你调用 emit() 时,就会把所发送的值传给订阅上来的观察者的 next() 方法。

EventEmitter 与指令@Output 一起在组件中使用以同步或异步方式发送自定义事件,并通过订阅实例来注册这些事件的处理程序。

ts 复制代码
EventEmitter语法:
emit() : 发出包含给定值的事件。
subscribe(): 注册此实例发出的事件的处理器
  1. 子组件
ts 复制代码
// 1.html
    <div class="zippy">
        <div (click)="toggle()">点击该文本</div>
        <div [hidden]="visible">
            <ng-content></ng-content>
        </div>
    </div> 

// 2.ts
export class ChildComponent {
  visible = true;
  // tslint:disable-next-line: no-output-native
  @Output() open = new EventEmitter<any>();
  // tslint:disable-next-line: no-output-native
  @Output() close = new EventEmitter<any>();
  
  toggle() {
    this.visible = !this.visible;
    if (this.visible) {
      this.close.emit('关闭');
    } else {
      this.open.emit('打开');
      this.open.subscribe((data) => {
        console.log('open subscribe:' + data);
      });
    }
  }
}
  1. 父组件: 子组件去运行 toggle()函数去赋值给 open 或者 close,父组件根据拿到的值去运行onOpen()或者onClose语句。
ts 复制代码
// 1.html
    <child (open)="onOpen($event)" (close)="onClose($event)">我是child组件的内容</child>

// 2. ts
export class ParentComponent {
  onOpen(e) {
    console.log(e);
  }
  onClose(e) {
    console.log(e);
  }
}
@ViewChild

@ViewChild 可以获取到当前组件视图中的单个元素

ts 复制代码
@ViewChild('selector', {read: ElementRef, static: false})  selector; 
1. selector - 要查询的指令类型或名称。
2. read - 用于从查询到的元素中读取不同的令牌。
3. static - 如果为 true,则在变更检测运行之前解析查询结果,如果为 false,则在变更检测之后解析。默认为 false。

// eg:1
字符串形式的模板引用变量(比如可以使用 @ViewChild('cmp') 来查询 <my-component #cmp></my-component>
里面的cmp就是模板应用变量

// eg:2 
我想通过#myname去查询原始,并将返回ViewContainerRef类型
@ViewChild('myname', {read: ViewContainerRef}) target; 

例子如下:

ts 复制代码
// 1.home.html
    <p #myLabel>icon</p>
// 2. home.ts
export class HomePage {
  @ViewChild('myLabel') temp;
  ngAfterViewInit(): void {
    console.log(this.temp);} // ElementRef {nativeElement: p}
}
@ViewChildren获取子组件对象列表

管道

PIPE,翻译为管道。Angular 管道是编写可以在HTML组件中声明的显示值转换的方法。Angular 管道之前在 AngularJS 中被称为过滤器,从 Angular 2 开始就被称为管道。管道将数据作为输入并将其转换为所需的输出。

简单来说,就是 Angular Pipes 可以帮我们把我们的输入,包括字符串,整数和日期等等,按照我们的需要转化为特定的格式并且在浏览器中显示。通过插值表达式,我们可以定义管道并且在特定的情况下使用它,在 Angular 中提供给了我们许多种不同类型的管道,当然,你甚至还可以去自定义管道。

更多管道官当网址

总结:管道就是一个方法,可以将你的输入转化为特定的你需要的输出格式,Angular提供给了我们许多的内置管道,当内置管道不满足你的要求的时候,你还可以通过自定义管道来更加灵活的自定义输出格式。

1.时间管道

ts 复制代码
// 1. html 
    {{date }}  // Mon Jan 08 2024 09:41:10 GMT+0800 (中国标准时间)
    <br> 
    {{date | date:'yyyy-MM-dd'}} //  2024-01-08

// 2. ts
export class HomePage {
  date = new Date();
}
  1. 货币管道
ts 复制代码
// 1.html
    <p>A: {{a | currency}}</p>  <!-- A: $0.26 -->
    <p>A: {{a | currency:'CAD'}}</p> <!-- A: CA$0.26 -->
    <p>A: {{a | currency:'CAD':'code'}}</p> <!-- B: CA$0,001.35 -->
    <p>B: {{b | currency:'CAD':'symbol':'4.2-2'}}</p> <!-- B: CA$0,001.35 -->
    <p>B: {{b | currency:'CAD':'symbol-narrow':'4.2-2'}}</p> <!-- B: $0,001.35 -->
    <p>B: {{b | currency:'CLP'}}</p> <!-- B: CLP1.35 -->

// 2.ts
export class HomePage {
  a: number = 0.259;
  b: number = 1.3495;
}
  1. 自定义管道
ts 复制代码
// 1. 创建指令
ng g p pipes/pipe-name
// ionic
ionic g + pipe + name

// 2. app.module.ts配置(本次的例子是基于ionic3框架)
import {PipesModule} from '../pipes/pipes.module';
  imports: [ 
    PipesModule,
    IonicModule.forRoot(MyApp)
  ],
// 3. pipes/test/test/ts
@Pipe({
  name: 'test', // 这个name用于下面html的管道名称
})
export class TestPipe implements PipeTransform {
  transform(value: string, ...args) {
    let value1 = "test"+value;
    return value1;
  }
}

// pages/home.html
{{lemon | test}}

常用模块

Angular 应用至少需要一个充当根模块使用的模块。 如果你要把某些特性添加到应用中,可以通过添加模块来实现。

参考文档

1\] [W3CSchool](https://www.w3cschool.cn/angular13/) \[2\] [官网 - 父子组件](https://angular.cn/guide/inputs-outputs)

相关推荐
changuncle4 天前
Angular初学者入门第一课——搭建并改造项目(精品)
javascript·ecmascript·angular.js
IT布道13 天前
解决angular与jetty websocket 每30s自动断连的问题
websocket·angular.js·jetty
葡萄城技术团队19 天前
在 Angular 应用程序中使用 Genkit 的完整指南
前端·angular.js
界面开发小八哥21 天前
界面控件Kendo UI for Angular 2025 Q2新版亮点 - 增强跨设备的无缝体验
前端·ui·界面控件·kendo ui·angular.js
蓝乐21 天前
Angular项目IOS16.1.1设备页面空白问题
前端·javascript·angular.js
欧阳天羲24 天前
Angular 框架下 AI 驱动的企业级大前端应用开
前端·人工智能·angular.js
甜瓜看代码1 个月前
1.
react.js·node.js·angular.js
天若有情6731 个月前
React、Vue、Angular的性能优化与源码解析概述
vue.js·react.js·angular.js
啃火龙果的兔子1 个月前
Angular 从框架搭建到开发上线的完整流程
前端·javascript·angular.js
葡萄城技术团队1 个月前
Angular V20 新特性
angular.js