在Angular中,可以使用@Input装饰器将数据从父组件传递给子组件。
首先,在父组件中定义一个属性,并使用@Input装饰器将其标记为可接收的输入属性。例如,假设我们在父组件中有一个名为"parentData"的属性:
import { Component } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
`
})
export class ParentComponent {
parentData: string = "Hello from parent";
}
然后,在子组件中,使用@Input装饰器来接收父组件传递的数据。我们可以在子组件的类中定义一个名为"childData"的属性:
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
template: `
{{ childData }}
`
})
export class ChildComponent {
@Input() childData: string;
}
现在,当父组件加载时,它会将"parentData"属性的值传递给子组件的"childData"属性。在子组件的模板中,我们可以使用插值表达式来显示子组件接收到的数据。
最后,在父组件的模板中,使用子组件的选择器来引用子组件,并将父组件的属性绑定到子组件的输入属性上。
这样,当父组件加载时,子组件将接收到父组件传递的数据,并将其显示在视图中。
注意:要使上述代码生效,需要在父组件和子组件所在的模块中正确导入和声明这些组件。