[Angular 2] @Input & @Output Event with ref
The application is simple, to build a color picker:
When click the rect box, it will check the color value below and title color will also change.
color-picker.ts:
import {Component, Output, EventEmitter, Input} from "@angular/core"; import {RED, BLUE} from './constants'; @Component({ selector: 'color-picker', moduleId: module.id, templateUrl: 'color-picker.component.html' }) export class ColorPicker{ @Input() color:string; @Output('selectedColor') colorOut = new EventEmitter(); red = RED; blue = BLUE; choose(color){ this.colorOut.emit(color); } }
color-picker.component.html:
<div class="color-title" [ngStyle]="{color:color}">Pick a Color, plz:</div> <div class="color-picker"> <div class="color-sample color-sample-blue" (click)="choose(red)"></div> <div class="color-sample color-sample-red" (click)="choose(blue)"></div> </div>
So the logic is we will take a color input, it is used in title styling:
<div class="color-title" [ngStyle]="{color:color}">Pick a Color, plz:</div>
When we click on one rect box, fire choose() function, it will output a event named "selectedColor":
@Output('selectedColor') colorOut = new EventEmitter(); choose(color){ this.colorOut.emit(color); }
If we don't give name 'selectorColor', it will used 'colorOut' as name.
In app.ts, it is used:
<color-picker #picker [color]="picker.color" (selectedColor)="picker.color = $event">
</color-picker>
{{picker.color}}
Here we use reference:
#picker
And we assign the color back from output event to picker.color, this picker.color then will be used as input to color-pick to change the title color.
The benfits to use reference is avoid assign a local variable.
分类:
Angular
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 记一次.NET内存居高不下排查解决与启示
· 探究高空视频全景AR技术的实现原理
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!
· AI技术革命,工作效率10个最佳AI工具