在Angular中,@Input装饰器用于接收来自父组件的值。父组件可以通过属性绑定将值传递给子组件。
下面是一个示例,展示了如何使用@Input装饰器:
在子组件中,我们创建一个名为ChildComponent的组件,它有一个名为inputValue的输入属性:
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
template: '{{ inputValue }}
'
})
export class ChildComponent {
@Input() inputValue: string;
}
在父组件中,我们创建一个名为ParentComponent的组件,并将一个值传递给子组件的inputValue属性:
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: ' '
})
export class ParentComponent {
parentValue = 'Hello from parent component';
}
在这个例子中,父组件的parentValue属性的值被绑定到子组件的inputValue属性。子组件接收并显示该值。
请注意,子组件的inputValue属性必须使用@Input装饰器进行标记,以便Angular能够识别它作为一个输入属性。
这是通过属性绑定将值传递给子组件的一种常见方法。当父组件的属性值发生变化时,子组件将自动更新以反映这些变化。