angular8 — 父子组件之前的通信

1. 子组件传值给父组件

子组件:invest-profile-left.component.ts(子组件的html页面不需要其他操作)

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

@Component({
  selector: 'kt-invest-profile-left',
  templateUrl: './invest-profile-left.component.html',
  styleUrls: ['./invest-profile-left.component.scss']
})
export class InvestProfileLeftComponent implements OnInit {
  @Output() taskData = new EventEmitter;
  constructor() {
  }

  ngOnInit() {
  	this.taskData.emit("我是在子组件中获取到的值,需要传给父组件");
  }
}

父组件:investment-profile.component.html

<div>
	<kt-invest-profile-left (taskData)="getTaskData($event)"></kt-invest-profile-left>
	<kt-invest-profile-tasks></kt-invest-profile-tasks>
</div>

父组件:investment-profile.component.ts

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

@Component({
  selector: 'kt-investment-profile',
  templateUrl: './investment-profile.component.html',
  styleUrls: ['./investment-profile.component.scss']
})
export class InvestmentProfileComponent implements OnInit {
  public taskData;
  constructor() { 
  }
  ngOnInit() {
  }
  public getTaskData($event) {
    this.taskData = $event;	// 获取到子组件传过来的值,并把值存入变量taskData 
  }
}

到此已完成子组件给父组件传值

2. 父组件传值给子组件(我就把父组件刚刚接收到的值传给其它子组件好了)

父组件:investment-profile.component.html

<div>
	<kt-invest-profile-left (taskData)="getTaskData($event)"></kt-invest-profile-left>
	<kt-invest-profile-tasks [taskData]="taskData"></kt-invest-profile-tasks>
</div>

子组件:invest-profile-tasks.component.ts

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

@Component({
  selector: 'kt-invest-profile-tasks',
  templateUrl: './invest-profile-tasks.component.html',
  styleUrls: ['./invest-profile-tasks.component.scss']
})
export class InvestProfileTasksComponent implements OnInit {
  @Input() taskData;	// 接收父组件传过来的值
  constructor() {
  }
  ngOnInit() {}
}
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
Angular 中,组件间的父子传值可以通过输入属性(@Input)和输出属性(@Output)来实现。 1. 父组件向子组件传值(通过输入属性): - 在子组件的类中,使用 `@Input()` 装饰器定义一个输入属性,例如 `@Input() value: string;`。 - 在父组件的模板中,使用子组件的标签,并通过绑定属性的方式将值传递给子组件,例如 `<app-child [value]="parentValue"></app-child>`。 2. 子组件向父组件传值(通过输出属性和事件): - 在子组件的类中,使用 `@Output()` 装饰器定义一个输出属性,并创建一个事件发射器,例如 `@Output() valueChange: EventEmitter<string> = new EventEmitter<string>();`。 - 在子组件中的某个适当的时机,调用事件发射器的 `emit()` 方法来触发事件,并传递需要传递给父组件的值,例如 `this.valueChange.emit(newValue);`。 - 在父组件的模板中,使用子组件的标签,并绑定相应的事件处理函数来接收子组件发出的事件,例如 `<app-child (valueChange)="onChildValueChange($event)"></app-child>`。在父组件的类中,实现名为 `onChildValueChange()` 的事件处理函数来处理子组件传递过来的值。 通过上述方式,父组件和子组件之间可以进行简单和复杂的数据传递,并实现双向通信。这种组件通信的方式可以有效地在 Angular 应用程序中传递和共享数据,以实现组件之间的交互和协作。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值