MST

星途 面试题库

面试题:Angular组件中@Input和@Output装饰器的使用

请详细说明Angular组件中@Input和@Output装饰器的作用,在父子组件通信场景下,如何正确使用它们来传递数据和事件?请举例说明。
12.4万 热度难度
前端开发Angular

知识考点

AI 面试

面试题答案

一键面试

@Input装饰器的作用

  1. 数据流入组件@Input装饰器用于将数据从父组件传递到子组件。它允许父组件向子组件传递数据,使得子组件能够接收并使用父组件提供的值。
  2. 属性绑定:在父组件的模板中,通过属性绑定的方式将数据传递给子组件中使用@Input装饰的属性。

在父子组件通信中使用@Input传递数据的示例

  1. 子组件定义
import { Component, Input } from '@angular/core';

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

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

@Output装饰器的作用

  1. 事件流出组件@Output装饰器用于让子组件向父组件发送事件。子组件可以在特定情况下触发一个事件,父组件可以监听这个事件并做出相应的处理。
  2. 事件绑定:在父组件模板中,通过事件绑定的方式监听子组件发出的事件。

在父子组件通信中使用@Output传递事件的示例

  1. 子组件定义
import { Component, Output, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-child',
  templateUrl: './child.component.html',
  styleUrls: ['./child.component.css']
})
export class ChildComponent {
  @Output() childEvent = new EventEmitter();

  sendEvent() {
    this.childEvent.emit('子组件触发了事件');
  }
}
  1. 子组件模板(child.component.html)
<button (click)="sendEvent()">触发事件</button>
  1. 父组件模板(parent.component.html)
<app-child (childEvent)="handleChildEvent($event)"></app-child>
  1. 父组件定义(parent.component.ts)
import { Component } from '@angular/core';

@Component({
  selector: 'app-parent',
  templateUrl: './parent.component.html',
  styleUrls: ['./parent.component.css']
})
export class ParentComponent {
  handleChildEvent(data: string) {
    console.log('接收到子组件的事件数据:', data);
  }
}