簡體   English   中英

在角度6中調用子組件方法

[英]calling child component method in angular 6

我正在嘗試從父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>

您可以使用@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();
  }
} 

希望這會有所幫助

我相信您忘記在父模板文件中添加子組件選擇器。

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");
    }
 }

希望這能解決您的問題!

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

讓我們,您的AddComponent的選擇器是add-component。 因此,請像下面在HTML / template-中這樣稱呼它-

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM