MST
星途 面试题库

面试题:Angular组件交互之父子组件通信

在Angular中,描述一下父子组件之间如何进行数据传递和事件通信?请分别阐述从父组件到子组件传递数据,以及子组件向父组件传递数据的实现方式,并举例说明。
31.5万 热度难度
前端开发Angular

知识考点

AI 面试

面试题答案

一键面试

从父组件到子组件传递数据

  1. 使用@Input装饰器
    • 原理:在子组件中通过@Input()装饰器来定义一个输入属性,父组件可以通过绑定该属性来传递数据。
    • 示例
      • 子组件(child.component.ts)
import { Component, Input } from '@angular/core';

@Component({
  selector: 'app - child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent {
  @Input() parentData: string;
}
 - **子组件模板(child.component.html)**:
<p>从父组件接收到的数据: {{parentData}}</p>
 - **父组件(parent.component.ts)**:
import { Component } from '@angular/core';

@Component({
  selector: 'app - parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent {
  dataToChild = '这是来自父组件的数据';
}
 - **父组件模板(parent.component.html)**:
<app - child [parentData]="dataToChild"></app - child>

从子组件向父组件传递数据

  1. 使用@Output装饰器和EventEmitter
    • 原理:在子组件中通过@Output()装饰器和EventEmitter类来定义一个事件输出,当子组件中某些逻辑触发时,通过EventEmitteremit方法发射数据,父组件通过绑定该事件来接收子组件传递的数据。
    • 示例
      • 子组件(child.component.ts)
import { Component, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app - child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent {
  @Output() childData = new EventEmitter<string>();
  sendDataToParent() {
    this.childData.emit('这是来自子组件的数据');
  }
}
 - **子组件模板(child.component.html)**:
<button (click)="sendDataToParent()">点击向父组件发送数据</button>
 - **父组件(parent.component.ts)**:
import { Component } from '@angular/core';

@Component({
  selector: 'app - parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent {
  receivedData: string;
  handleChildData(data: string) {
    this.receivedData = data;
  }
}
 - **父组件模板(parent.component.html)**:
<app - child (childData)="handleChildData($event)"></app - child>
<p>从子组件接收到的数据: {{receivedData}}</p>