Angular应用双向绑定的语法糖
2023-09-14 09:04:03 时间
Angular[()]的语法暗示了element具有一个可以赋值的名为x的property,以及一个对应的xChange事件。
一个例子:
import { Component, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app-sizer',
templateUrl: './sizer.component.html',
styleUrls: ['./sizer.component.css']
})
export class SizerComponent {
@Input() size: number | string;
@Output() sizeChange = new EventEmitter<number>();
dec() { this.resize(-1); }
inc() { this.resize(+1); }
resize(delta: number) {
this.size = Math.min(40, Math.max(8, +this.size + delta));
this.sizeChange.emit(this.size);
}
}
size Component的size属性加上了@Input注解,使得parent Component在显示它的时候,可以进行property binding. sizeChange通过@Output修饰,这样可以给external receiver发送event.
parent Component的fontSizePx同child Component的size property进行双向绑定。
<app-sizer [(size)]="fontSizePx"></app-sizer>
<div [style.font-size.px]="fontSizePx">Resizable Text</div>
AppComponent的fontSizePx通过双向绑定的方式关联到了SizerComponent.
这个[(size)]的语法只是一个语法糖,实际会被转换成如下代码:
<app-sizer [size]="fontSizePx" (sizeChange)="fontSizePx=$event"></app-sizer>
The $event variable contains the payload of the SizerComponent.sizeChange event. Angular assigns the $event value to the AppComponent.fontSizePx when the user clicks the buttons.
相关文章
- [Angular 14] Inject() function
- [Angular RxJS] Single data observable pattern (combineLatest with startWith)
- [Angular] Use Angular’s @HostBinding and :host(...) to add styling to the component itself
- [Angular] Use Angular style sanitization to mark dynamic styles as trusted values
- [Immutable + AngularJS] Use Immutable .List() for Angular array
- [Angular] The $any() type cast function
- [Angular 8 Unit Testing] Testing a dump component
- [Angular + TsLint] Disable directive selector tslint error
- [Angular] Use Angular’s @HostBinding and :host(...) to add styling to the component itself
- [Angular 2] Generate and Render Angular 2 Template Elements in a Component
- [Angular 2] Using the @Inject decorator
- SAP Spartacus B2B user列表对应的Angular Component
- Angular SSR 应用启动时的一些保护措施
- 关于 Angular 项目里的 index.ts
- 运行在 CCV2 环境上的 Angular 服务器端渲染应用的性能瓶颈分析
- Angular应用里HTTP请求的错误处理
- Angular SSR 应用启动时的一些保护措施
- Angular 里 HTTP 请求和响应结构的拦截器(interceptors)在 SAP Spartacus 中的应用
- 关于 Angular PWA 应用中的 ngsw.json 文件
- 使用 NgRX Store Module 给 Angular 应用开发带来的收益
- 关于 Angular 应用 Module 的 forRoot 方法的讨论
- 运行在 SSR 模式下的 Angular 应用的内存泄漏问题分析
- Angular 应用里的摇树优化 - tree shaking
- Angular 应用里的 vendor.js 是用来干什么的?
- Angular 服务器端渲染的学习笔记(二)
- Angular应用启动时创建的injection token一览
- Angular应用动态创建style标签页的场景
- 如何处理Angular应用的错误消息: No pipe found with name async
- 使用Stackblitz一分钟之内创建一个Angular应用