简体   繁体   中英

viewchild component is undefined

i'm trying to develop my first angular app and i'm running into trouble. I got the following code sample

AbstractComponent.ts

  export interface IComponent {
     getPageTitle(): string;
  }
    
  export abstract class AbstractComponent implements IComponent {
     getPageTitle(): string {
       throw new Error("Method not implemented.");
     }
  }

FirstComponent.ts

  export class FirstComponent implements OnInit, AbstractComponent {
  // do something
  }

  @Component({
    selector: 'app-root',
    templateUrl: './app.component.html',
    styleUrls: ['./app.component.scss']
  })
  export class AppComponent implements OnInit, AfterViewInit {

  @ViewChild(AbstractComponent) child: IComponent;
    // ...
    onButtonClicked(): void {
      console.log(this.child);
      console.log(this.child.getPageTitle());
  }

app.component.html

  <header>
    <!-- some header stuff --> 
  </header>
  <main>
    <router-outlet></router-outlet>
    <!-- some main stuff -->
  </main>

Why is "this.child" always empty? Is it possible to call a method of a child component in parent component.

From my perspective you're using @ViewChild() wrong here. You always need a hash tag in the HTML-template in order to reference to the child.

Something like this

HTML-Template

<my-component #myChild>
    <!-- some other HTML -->
</my-component>

TS-File

@ViewChild('myChild') child: IComponent;

Here is what the makers of Angular have to say: https://angular.io/api/core/ViewChild

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM