Angular13父子组件不通信
创始人
2024-10-21 23:01:32
0

1.利用@Input()和@Output()装饰器在父子组件之间进行通信。

在子组件中,使用@Input()装饰器将从父组件接收到的数据绑定到组件中的相应变量上:

import { Component, Input } from '@angular/core';

@Component({ selector: 'child-component', template: '{{childInfo}}' }) export class ChildComponent { @Input() childInfo: string; }

在父组件中,使用@Output()装饰器和EventEmitter实例来触发自定义事件,将数据发送到子组件:

import { Component, EventEmitter, Output } from '@angular/core';

@Component({ selector: 'parent-component', template: '' }) export class ParentComponent { parentData: string = 'Hello, child!';

@Output() dataEvent = new EventEmitter();

sendData() { this.dataEvent.emit(this.parentData); } }

2.使用服务来在组件之间进行通信

创建服务:

import { Injectable } from '@angular/core'; import { Subject } from 'rxjs';

@Injectable({ providedIn: 'root' }) export class DataService { private dataSource = new Subject(); data$ = this.dataSource.asObservable();

sendData(data: string) { this.dataSource.next(data); } }

在父组件中注入服务并使用sendData()方法发送数据:

import { Component } from '@angular/core'; import { DataService } from './data.service';

@Component({ selector: 'parent-component', template: '' }) export class ParentComponent { parentData: string = 'Hello, child!';

constructor(private dataService: DataService) {}

sendData() { this.dataService.sendData(this.parentData); } }

在子组件中注入服务并使用data$可观察对象订阅数据:

import { Component } from '@angular/core'; import { DataService } from './data.service';

@Component({ selector: 'child-component',

相关内容

热门资讯

3分钟法门!如何判断wpk辅助... 3分钟法门!如何判断wpk辅助软件的真假(透视)原来是真的有辅助教程(哔哩哔哩)1、起透看视 如何判...
第6分钟演示!wepoker如... 第6分钟演示!wepoker如何设置透视(透视)一直有辅助开挂(哔哩哔哩)1、超多福利:超高返利,海...
一分钟手册!佛手在线有挂吗(透... 一分钟手册!佛手在线有挂吗(透视)其实是真的有辅助透视(哔哩哔哩)1、下载好佛手在线有挂吗正确养号方...
5分钟烘培!aapoker a... 5分钟烘培!aapoker ai插件(透视)真是是真的有辅助开挂(哔哩哔哩)1、不需要AI权限,帮助...
6分钟攻略!悦扑克脚本(透视)... 6分钟攻略!悦扑克脚本(透视)其实是有辅助透视(哔哩哔哩)1、悦扑克脚本辅助器安装包、悦扑克脚本辅助...
第4分钟窍门!wpk系统是否存... 第4分钟窍门!wpk系统是否存在作必弊行为(透视)其实真的有辅助插件(哔哩哔哩)wpk系统是否存在作...
第7分钟机巧!wepoker透... 第7分钟机巧!wepoker透视最简单三个步骤(透视)本来是有辅助辅助(哔哩哔哩)1、操作简单,无需...
七分钟项目!wepoker透视... 七分钟项目!wepoker透视脚本视频(透视)本来是有辅助开挂(哔哩哔哩)1、wepoker透视脚本...
第2分钟方式!德普之星辅助器a... 第2分钟方式!德普之星辅助器app(透视)竟然是有辅助神器(哔哩哔哩)1、德普之星辅助器app模拟器...
6分钟窍门!wepoker俱乐... 6分钟窍门!wepoker俱乐部辅助(透视)都是真的是有辅助下载(哔哩哔哩)1、超多福利:超高返利,...