angular开发从入门到入土第二节(组件通信)
一.input和output
1.子组件通过@Input装饰器获取到父组件传递的值
//子组件html模板
<p>child</p> <div> {{ showText }} </div>
子组件类
import { ChangeDetectionStrategy, Component, Input } from '@angular/core'; @Component({ selector: 'app-my-com', templateUrl: './my-com.component.html', styleUrls: ['./my-com.component.less'], changeDetection: ChangeDetectionStrategy.OnPush }) export class MyComComponent { @Input() showText = '' }
父类通过输入框来改写传递的值
效果:在父组件的值修改的值传递到子组件
2.子组件通过@output装饰器把值传递到父组件
父组件html模板
<p>father</p> <input nz-input [(ngModel)]="inputText" /> <div> childText {{childText}}</div> <app-my-com [showText]="inputText" (changeShowText)="childgetFn($event)"></app-my-com>
父组件类
import { ChangeDetectionStrategy, Component } from '@angular/core'; @Component({ selector: 'app-page1', templateUrl: './page1.component.html', styleUrls: ['./page1.component.less'], changeDetection: ChangeDetectionStrategy.OnPush }) export class Page1Component { inputText = '' childText = '' childgetFn($event:any){ this.childText = $event } }
子组件模板
<p>child</p>
<div>
chiidshow{{ showText }}
</div>
childinput<input nz-input [(ngModel)]="showText" (ngModelChange)="childChange()">
子组件类
import { ChangeDetectionStrategy, Component, EventEmitter, Input, Output } from '@angular/core';
@Component({
selector: 'app-my-com',
templateUrl: './my-com.component.html',
styleUrls: ['./my-com.component.less'],
changeDetection: ChangeDetectionStrategy.OnPush
})
export class MyComComponent {
@Input() showText = ''
@Output() changeShowText = new EventEmitter()
childChange(){
this.changeShowText.emit(this.showText)
}
}
子组件输入框通过output触发父类方法,父类以此获取到子组件传递的值
3.通过input和output实现父子组件双向绑定
父组件
子组件
子组件类
效果
Angular 中 []
实现了模型到视图的数据绑定,()
实现了视图到模型的事件绑定。把它们两个结合在一起 [()]
就实现了双向绑定。也被称为 banana in a box
语法。
4.通过viewChild 获取子组件值
父类通过viewChild 获取到子组件值
5.通过实现ControlValueAccessor接口实现自定义组件(有空再写)
6.通过服务实现数据共享和组件通信
child1去订阅服务中的obs
child2注册为public service,并去掉onpush策略(使用了onpush策略,不触发detectChanges()方法,视图默认无需更新,去掉onpush策略时,angular通过ngzone补获到异步事件,会自动触发detectchanges方法,以此更新视图)
父组件input框,ngModelChange绑定changeService方法
通过setObs去传递值给child1通过改变showText去改变child2展示的值
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· 阿里最新开源QwQ-32B,效果媲美deepseek-r1满血版,部署成本又又又降低了!
· AI编程工具终极对决:字节Trae VS Cursor,谁才是开发者新宠?
· 开源Multi-agent AI智能体框架aevatar.ai,欢迎大家贡献代码
· Manus重磅发布:全球首款通用AI代理技术深度解析与实战指南
· 被坑几百块钱后,我竟然真的恢复了删除的微信聊天记录!