简体   繁体   English

viewchild 组件未定义

[英]viewchild component is undefined

i'm trying to develop my first angular app and i'm running into trouble.我正在尝试开发我的第一个 angular 应用程序,但遇到了麻烦。 I got the following code sample我得到了以下代码示例

AbstractComponent.ts抽象组件.ts

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

FirstComponent.ts第一个组件.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 app.component.html

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

Why is "this.child" always empty?为什么“this.child”总是空的? Is it possible to call a method of a child component in parent component.是否可以在父组件中调用子组件的方法。

From my perspective you're using @ViewChild() wrong here.从我的角度来看,您在这里使用了错误的@ViewChild() You always need a hash tag in the HTML-template in order to reference to the child.您始终需要在 HTML 模板中使用 hash 标记才能引用子项。

Something like this像这样的东西

HTML-Template HTML 模板

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

TS-File TS-文件

@ViewChild('myChild') child: IComponent;

Here is what the makers of Angular have to say: https://angular.io/api/core/ViewChild这是 Angular 的制造商不得不说的: https://angular.io/api/core/ViewChild

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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