在Angular中,可以通过使用@Input装饰器将父组件的数据传递给子组件。以下是一个示例:
在父组件中,定义一个存储数据的属性,并使用@Input装饰器将其暴露给子组件:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
`
})
export class ParentComponent implements OnInit {
parentData: string = 'Hello from parent';
constructor() { }
ngOnInit(): void {
}
}
在子组件中,使用@Input装饰器接收父组件传递的数据:
import { Component, Input, OnInit } from '@angular/core';
@Component({
selector: 'app-child',
template: `
{{ data }}
`
})
export class ChildComponent implements OnInit {
@Input() data: string;
constructor() { }
ngOnInit(): void {
}
}
在父组件的模板中,通过使用方括号将父组件的属性绑定到子组件的输入属性上。在上面的例子中,父组件的parentData属性被绑定到子组件的data属性。
这样,当父组件的parentData属性发生变化时,子组件的data属性也会相应地更新,从而在子组件的模板中显示最新的数据。
请注意,父组件的模板中使用的选择器
是子组件的选择器。确保在父组件的模板中正确引用子组件。