Angular 学习笔记 (二) - 数据绑定
一. 变量绑定
element in html template 和 component variable 的绑定有以下两种形式:
<span>{{ title }}</span> <span [innerText]="title"></span>
也可以用来绑定变量为object的成员
<p [innerText]="mystruct.name"></p>
设置HTML element的属性:
<p [attr.aria-label]="myText"></p>
二. Style设置
在HTML模板中,可以设置style和class
<p class="currentClasses"></p> <p style="color: greenyellow"></p>
class可以在ts中定义:
1 currentClasses = { 2 star: true, 3 active: false 4 };
另外一种写法:
<p [class]="currentClasses"></p> <p [style.color]="'greenyellow'"></p> <p [style.width.px]="100"></p> <p [style]="currentStyle"></p>
三. 绑定函数
以button为例,Component中加入onClick()方法,被button触发:
<button (click)="onClick()">Click me</button>
事件绑定侦听在目标HTML元素上发生的DOM事件,并通过调用组件中相应的方法来响应这些事件。在这个在这种情况下,当用户单击按钮时,Component调用onClick方法。这个括号内的事件称为目标事件,是我们正在侦听的事件。
所支持的Event参考:https://developer.mozilla.org/en-US/docs/Web/Events.
四. Component之间的通讯
举例说明:
在src目录下新建一个Heroes component (ng g c Heroes),实现app component和它的通讯
1)在App html template中加入一个component,取名为app-hero: <app-hero></app-hero>.
2) 定义输入输出,在app component中定义输入:
import { Input } from '@angular/core'
@Input() name: string;
4.1 变量传递
在hero component中设置绑定:
<p>{{name}} hero works!</p>
可以通过下列方法,在app-component的html中进行赋值:
<app-hero name="Boothstomper"></app-hero> <app-hero [name]="hero"></app-hero>
4.2 函数调用
不同Component间相互调用需要使用Event来完成,这里实现点击Heroes-component的button来触发app-component
heroes-component定义:
@Output() liked = new EventEmitter();
需要import:import { Output, EventEmitter } from '@angular/core';
按钮中定义事件:
<button (click)="liked.emit()">Like</button>
app-component中定义输入
<app-hero [name]="hero" (liked)="onLike()"></app-hero>
onlike为app-component的触发函数
4.3 自定义事件
APPComponent中定义:
@Output() liked = new EventEmitter<boolean>();
Heroes-component中添加按钮事件:
<button (click)="liked.emit(true)">Like</button>
AppComponent触发事件
<app-hero [name]="hero" (liked)="onLike($event)"></app-hero>
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具