【问题标题】:calling child component method in angular 6在 Angular 6 中调用子组件方法
【发布时间】:2019-06-23 11:48:01
【问题描述】:

我正在尝试从父 ts 文件调用子组件方法,但我无法调用。收到错误无法读取未定义的属性“doSomething”。

 export class AddComponent implements OnInit, OnDestroy {
    public doSomething()
    {
       alert("Called");
    }
 }

父代码:

@ViewChild(AddComponent) child:AddComponent;
 ngAfterViewInit() {
 this.child.doSomething();
}

父 html 文件

<span class="glyphicon glyphicon-plus addBack" title="Add new booking" (click)=" openActionModal(GridActions, $event, null, 'add')"
      style="float: right;margin-right: 10px;margin-top: 18px;"></span>

<ng-template #GridActions>
    <div class="modal-header">

      <button type="button" class="close pull-right" aria-label="Close" (click)="openConfirmationModal(EditConfirmation)">
        <span aria-hidden="true">&times;</span>
      </button>
    </div>
    <div class="modal-body">
      <app-add #child *ngIf="showModalAdd"> </app-add>
    </div>

  </ng-template>

【问题讨论】:

标签: angular angular6


【解决方案1】:

我相信你忘了在你的父模板文件中添加子组件选择器。

parent.component.html

<add-component></add-component>

parent.component.ts

@ViewChild(AddComponent) child:AddComponent;
   ngAfterViewInit() {
   this.child.doSomething();
}

add.component.ts

export class AddComponent implements OnInit, OnDestroy {
    public doSomething()
    {
       alert("Called");
    }
 }

希望这能解决您的问题!

【讨论】:

  • 我在引导模式弹出窗口中调用子视图,我添加了它,但它不起作用。
  • 在模板模态标签和@ViewChild('referencevarname') child:AddComponent 中声明引用变量;在此处添加
  • 我已经声明了它但它仍然不起作用请检查我是否在问题中添加了 html 文件代码
【解决方案2】:

您可以使用@ViewChild 来做到这一点

@Component({
 selector: 'child-cmp',
 template: '<p>child</p>'
})
class ChildCmp {
   doSomething() {}
 }

@Component({
  selector: 'some-cmp',
  template: '<child-cmp></child-cmp>',
 directives: [ChildCmp]
})
class SomeCmp {
 @ViewChild(ChildCmp) child:ChildCmp;
 ngAfterViewInit() {
    // child is set
    this.child.doSomething();
  }
}

使用字符串选择器

@Component({
 selector: 'child-cmp',
 template: '<p>child</p>'
 })
class ChildCmp {
   doSomething() {}
}
@Component({
    selector: 'some-cmp',
    template: '<child-cmp #child></child-cmp>',
    directives: [ChildCmp]
})
class SomeCmp {
    @ViewChild('child') child:ChildCmp;
    ngAfterViewInit() {
    // child is set
    this.child.doSomething();
  }
} 

希望这会有所帮助

【讨论】:

    【解决方案3】:

    您是否在 HTML/模板中进行了引用?您需要进行模板引用才能调用 ViewChild-

    让你的 AddComponent 的选择器是 add-component。所以在 HTML/template 中像下面这样调用它-

    <add-component #child></add-component>
    

    【讨论】:

    • OP 的调用方式类似于 @ViewChild(AddComponent) ,因此无需定义模板变量,例如 #child。像@ViewChild('child', {read: AddComponent})这样调用时需要它
    猜你喜欢
    • 2019-04-03
    • 2017-09-05
    • 2019-05-15
    • 2020-10-20
    • 2023-01-08
    • 1970-01-01
    • 2016-12-22
    • 1970-01-01
    相关资源
    最近更新 更多