Angular中组件间通讯的实现方法
这篇文章主要介绍Angular中组件间通讯的实现方法,文中介绍的非常详细,具有一定的参考价值,感兴趣的小伙伴们一定要看完!
在宿松等地区,都构建了全面的区域性战略布局,加强发展的系统性、市场前瞻性、产品创新能力,以专注、极致的服务理念,为客户提供做网站、成都做网站 网站设计制作按需制作,公司网站建设,企业网站建设,品牌网站建设,网络营销推广,外贸网站制作,宿松网站建设费用合理。
Angular 组件间的通讯
组件间三种典型关系:
父好组件之间的交互(@Input/@Output/模板变量/@ViewChild)
非父子组件之间的交互(Service/localStorage)
还可以可以利用 Session、 路由参数来进行通讯等
相关教程推荐:《angular教程》
父子组件之间交互
子组件编写
child.component.ts
@Component({ selector: 'app-child', templateUrl: './child.component.html', styleUrls: ['./child.component.css'] }) export class ChildComponent implements OnInit { private _childTitle = '我是子组件'; @Input() set childTitle(childTitle: string) { this._childTitle = childTitle; } get childTitle(): string { return this._childTitle; } @Output() messageEvent: EventEmitter= new EventEmitter (); constructor() { } ngOnInit(): void { } sendMessage(): void { this.messageEvent.emit('我是子组件'); } childFunction(): void { console.log('子组件的名字是:' + this.childTitle); } }
child.component.html
{{childTitle}}
父组件
parent-and-child.component.ts
@Component({ selector: 'app-parent-and-child', templateUrl: './parent-and-child.component.html', styleUrls: ['./parent-and-child.component.css'] }) export class ParentAndChildComponent implements OnInit { constructor() { } ngOnInit(): void { } doSomething(event: any): void { alert(event); } }
parent-and-child.component.html
父组件