Avatar ·

Angular 2 @ViewChild يُرجع undefined — كيفية الوصول الصحيح إلى المكون الفرعي؟

مرحبًا بالجميع! أنا مبتدئ في Angular (2+) و TypeScript، وواجهت مشكلة تحيرني. أحاول الوصول إلى المكون الفرعي باستخدام decorator @ViewChild، لكنه دائمًا يُرجع undefined. إليك الكود الخاص بي. يوجد مكون أب `ParentComponent`: ```typescript import { Component, ViewChild, AfterViewInit } from '@angular/core'; import { ChildComponent } from './child.component'; @Component({ selector: 'app-parent', template: `
` }) export class ParentComponent { @ViewChild(ChildComponent) childComponent!: ChildComponent; callChildMethod() { if (this.childComponent) { this.childComponent.doSomething(); } else { console.log('childComponent is undefined'); } } } ``` والمكون الفرعي `ChildComponent`: ```typescript import { Component } from '@angular/core'; @Component({ selector: 'app-child', template: `

child works!

` }) export class ChildComponent { doSomething() { console.log('تم استدعاء دالة doSomething'); } } ```