
typescript
# Angular 中的 @Input() 用途及案例代码
在Angular中,@Input() 是一个装饰器,用于定义组件的输入属性。通过@Input() 装饰器,我们可以将数据从一个组件传递到另一个组件,实现组件之间的通信。这种机制是Angular中实现父子组件通信的一种重要方式。## 1. @Input() 的基本用法在一个组件中,我们可以通过@Input() 装饰器声明一个属性,使其成为可输入属性。这样,这个属性就可以接收来自父组件的值。typescript// child.component.tsimport { Component, Input } from '@angular/core';@Component({ selector: 'app-child', template: <code> <div> 子组件接收到的值: {{ inputValue }}
</div> </code>,})export class ChildComponent { @Input() inputValue: string;}在上述示例中,@Input() inputValue 声明了一个可输入属性,它将接收父组件传递过来的值。## 2. 父组件向子组件传递数据在父组件中,通过在子组件的标签中绑定属性的方式,将数据传递给子组件。typescript// parent.component.tsimport { Component } from '@angular/core';@Component({ selector: 'app-parent', template: <code> <div> <app-child [inputValue]="parentValue"></app-child> </div> </code>,})export class ParentComponent { parentValue = 'Hello from Parent!';}在这个例子中,[inputValue]="parentValue" 将父组件的 parentValue 数据传递给子组件的 inputValue 属性。## 3. 多个输入属性的使用有时,一个组件可能需要接收多个输入属性。这时,可以在组件中使用多个 @Input() 装饰器声明属性。typescript// complex-child.component.tsimport { Component, Input } from '@angular/core';@Component({ selector: 'app-complex-child', template: <code> <div> 属性1: {{ prop1 }}
属性2: {{ prop2 }}
</div> </code>,})export class ComplexChildComponent { @Input() prop1: string; @Input() prop2: number;}在父组件中,可以这样传递多个属性:typescript// complex-parent.component.tsimport { Component } from '@angular/core';@Component({ selector: 'app-complex-parent', template: <code> <div> <app-complex-child [prop1]="value1" [prop2]="value2"></app-complex-child> </div> </code>,})export class ComplexParentComponent { value1 = 'Property One'; value2 = 42;}通过这种方式,父组件可以方便地向子组件传递多个数据,实现更复杂的通信。## 在Angular中,@Input() 装饰器为组件之间的数据传递提供了强大而灵活的机制。通过声明可输入属性,我们能够实现父子组件之间的通信,使得组件更加模块化和可维护。这种方式是Angular框架中一项关键的特性,帮助开发者构建更加灵活和可复用的组件。希望这个简单的教程能够帮助你更好地理解和使用 @Input() 装饰器。Copyright © 2025 IZhiDa.com All Rights Reserved.
知答 版权所有 粤ICP备2023042255号