我在一个较大的项目中引用子组件时遇到了问题,因此我将这些组件放入项目中仅仅是为了我自己的理智检查 .
在任何情况下@ViewChild和@ViewChildren总是返回undefined . 我需要的是获得子元素的位置和尺寸......
我该怎么办才能解决这个问题?
Components are exported through a module...
Used in view like this
<app-parent>
<app-child></app-child>
</app-parent>
Child:
@Component({
selector: 'app-child',
template: `<div>Stuff</div>`,
})
export class ChildComponent {
constructor() { }
}
Parent:
@Component({
selector: 'app-parent',
template: `<div><ng-content></ng-content></div>`,
})
export class ParentComponent implements OnInit, AfterViewInit {
@ViewChild(ChildComponent) child: any;
@ViewChildren('app-child') childrenMethod: QueryList<ElementRef>;
constructor() { }
ngOnInit(): void {
console.log(this.child); // returns undefined
}
ngAfterViewInit() {
console.log(this.child); // returns undefined
this.childrenMethod.changes.subscribe(item => {
console.log('??' + this.childrenMethod); // nothing happens
});
}
是否有不同的方法来获取子元素,以便我可以使用它的位置和尺寸?