在Angular中,可以使用@Input
装饰器来实现类似于C#属性装饰器的功能。@Input
装饰器用于声明一个属性作为输入属性,在父组件中可以通过属性绑定的方式传递值给子组件。
以下是一个示例代码,展示了如何在Angular中使用@Input
装饰器:
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
template: `
Child Component
Received value: {{ inputValue }}
`
})
export class ChildComponent {
@Input() inputValue: string;
}
@Component({
selector: 'app-parent',
template: `
Parent Component
`
})
export class ParentComponent {
parentValue: string;
}
在上述示例中,ChildComponent
组件使用了@Input
装饰器来声明一个名为inputValue
的属性。该属性可以接收来自父组件的值。
ParentComponent
组件包含一个输入框,通过双向数据绑定的方式将输入框的值传递给ChildComponent
组件的inputValue
属性。
这样,当在输入框中输入值时,该值将传递给子组件,并在子组件中显示出来。
请注意,为了能够使用@Input
装饰器,需要在组件中导入Input
装饰器并从@angular/core
模块中引入。