Angular如何在父组件模板更改后从子组件调用方法?
创始人
2024-10-29 08:00:42
0

1.创建一个Output()事件,在父组件上触发该事件,然后在子组件中监听该事件。

父组件模板:


父组件组件类:

export class ParentComponent {
  // 父组件逻辑...

  onTemplateChange() {
    // 在模板更改后执行操作
  }
}

子组件组件类:

export class ChildComponent {
  @Output() templateChanged = new EventEmitter();

  ngAfterViewInit() {
    this.templateChanged.emit();
  }
}

当子组件的视图加载完成后,它会触发父组件上的Output()事件,父组件会收到该事件并执行其句柄中的方法。

2.使用ViewChild()获取子组件引用,并在父组件的AfterViewInit()生命周期中调用该方法。

父组件组件类:

import {AfterViewInit, Component, ViewChild} from '@angular/core';
import {ChildComponent} from './child.component';

export class ParentComponent implements AfterViewInit {
  @ViewChild(ChildComponent) childComponent: ChildComponent;

  ngAfterViewInit() {
    this.childComponent.callMethod();
  }
}

子组件组件类:

export class ChildComponent {
  callMethod() {
    // 子组件中调用的方法
  }
}

在父组件的生命周期中,使用ViewChild()获取子组件的引用,并在AfterViewInit()期间调用该方法。注意,子组件必须在此期间正确加载才能使用此方法。

相关内容

热门资讯

9分钟辅助!wepoker透视... 9分钟辅助!wepoker透视app下载,wepoker私人局俱乐部怎么进,方针教程(有挂工具)一、...
四分钟辅助!德普之星app安卓... 四分钟辅助!德普之星app安卓版破解版,wepokerplus脚本,项目教程(有挂辅助)1、玩家可以...
2分钟辅助!hhpoker透视... 2分钟辅助!hhpoker透视脚本,wepoker有透视吗,教程书教程(有挂头条)1、超多福利:超高...
第七分钟辅助!wepoker透... 第七分钟辅助!wepoker透视app下载,aa poker辅助包,讲义教程(有挂分享)一、wepo...
第八分钟辅助!wepoker怎... 第八分钟辅助!wepoker怎么开辅助,xpoker辅助器,模块教程(的确有挂)1、不需要AI权限,...
一分钟辅助!wepoker有没... 一分钟辅助!wepoker有没有挂,pokemmo脚本辅助器,讲义教程(有挂教学)1、完成pokem...
第一分钟辅助!hhpoker是... 第一分钟辅助!hhpoker是真的还是假的,wepoker辅助器,阶段教程(有挂技巧)1、金币登录送...
8分钟辅助!hhpoker辅助... 8分钟辅助!hhpoker辅助挂,wejoker私人辅助软件,窍要教程(有挂分析)1、玩家可以在we...
第6分钟辅助!xpoker透视... 第6分钟辅助!xpoker透视辅助,wejoker内置辅助,窍门教程(有挂秘诀)该软件可以轻松地帮助...
第六分钟辅助!aapoker公... 第六分钟辅助!aapoker公共底牌,aapoker怎么设置抽水,办法教程(真是有挂)1、在aapo...