在Angular中,可以通过使用Input和Output装饰器在组件之间传递值。以下是一个示例解决方法,其中一个组件将当前页面大小传递给另一个组件:
首先,创建一个父组件,用来获取页面大小并将其传递给子组件:
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-parent',
template: `
`,
})
export class ParentComponent implements OnInit {
pageSize: number;
ngOnInit() {
this.pageSize = window.innerWidth;
window.onresize = () => {
this.pageSize = window.innerWidth;
};
}
}
在该示例中,我们在父组件中使用window.innerWidth来获取当前页面的宽度,并将其赋值给pageSize变量。然后,我们将pageSize通过[currentValue]属性传递给子组件。
接下来,创建一个子组件,用来接收父组件传递的值并进行处理:
import { Component, Input } from '@angular/core';
@Component({
selector: 'app-child',
template: `
当前页面大小: {{ currentValue }}
`,
})
export class ChildComponent {
@Input() currentValue: number;
}
在子组件中,我们使用@Input装饰器来接收父组件传递的值,并将其赋值给currentValue变量。然后,我们可以在模板中使用currentValue来显示当前页面的大小。
确保在父组件中正确引入和注册子组件,然后在适当的位置添加父组件的标签,即可完成传递值的操作。
希望这个示例能够帮助你解决 currentValue 未定义错误的问题。