面试题答案
一键面试@Input装饰器
使用场景
用于将数据从父组件传递到子组件。通常在子组件需要接收外部数据来进行渲染或处理时使用。例如,子组件是一个显示用户信息的卡片,需要从父组件传入用户数据来填充卡片内容。
数据流向
数据是单向流动的,从父组件流向子组件。父组件设置数据,子组件接收并使用该数据。
使用方式
- 在子组件类中,使用
@Input()
装饰器修饰一个属性,这个属性用来接收父组件传递的数据。 - 在父组件的模板中,通过属性绑定的方式将数据传递给子组件。
代码示例
子组件(user - card.component.ts)
import { Component, Input } from '@angular/core';
@Component({
selector: 'app - user - card',
templateUrl: './user - card.component.html'
})
export class UserCardComponent {
@Input() user: { name: string; age: number };
}
子组件模板(user - card.component.html)
<div>
<p>Name: {{ user.name }}</p>
<p>Age: {{ user.age }}</p>
</div>
父组件模板(app.component.html)
<app - user - card [user]="{name: 'John', age: 30}"></app - user - card>
@Output装饰器
使用场景
用于子组件向父组件传递事件。当子组件发生某个事件,希望父组件能知晓并进行相应处理时使用。比如,子组件是一个按钮,点击按钮时要通知父组件执行某些操作。
数据流向
数据同样是单向流动,但方向是从子组件流向父组件,通过事件的形式传递。
使用方式
- 在子组件类中,使用
@Output()
装饰器修饰一个EventEmitter
类型的属性,EventEmitter
用于发射事件。 - 在子组件中合适的地方调用
EventEmitter
的emit
方法来触发事件,并传递数据(如果需要)。 - 在父组件模板中,通过事件绑定的方式监听子组件的事件,并定义相应的处理函数。
代码示例
子组件(button.component.ts)
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'app - button',
templateUrl: './button.component.html'
})
export class ButtonComponent {
@Output() buttonClick = new EventEmitter();
onClick() {
this.buttonClick.emit();
}
}
子组件模板(button.component.html)
<button (click)="onClick()">Click me</button>
父组件模板(app.component.html)
<app - button (buttonClick)="handleButtonClick()"></app - button>
父组件(app.component.ts)
import { Component } from '@angular/core';
@Component({
selector: 'app - root',
templateUrl: './app.component.html'
})
export class AppComponent {
handleButtonClick() {
console.log('Button in child component was clicked');
}
}
区别总结
- 数据流向:
@Input
是从父组件到子组件的单向数据传递,用于传递数据;@Output
是从子组件到父组件的单向数据传递,通过事件的形式传递信息。 - 使用目的:
@Input
主要用于子组件接收外部数据进行渲染或处理;@Output
主要用于子组件通知父组件某个事件发生。 - 修饰对象:
@Input
修饰子组件用于接收数据的属性;@Output
修饰子组件中类型为EventEmitter
的属性,用于发射事件。