微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何要求子组件访问它的 html 模板并使用组件的类实例在父组件的 UI 上显示某些内容?

如何解决如何要求子组件访问它的 html 模板并使用组件的类实例在父组件的 UI 上显示某些内容?

我正在做一个项目,其中, 我有 2 个组件:

  1. 主要组件,
  2. 弹出组件

主要组件 TS:

popupCompo = new popupComponent();

onButtonClick() {
   popupCompo.showModal();
}

弹出组件 TS :

==> HTML

<ng-template #popup>
...
</ng-template>

==> TS:

@Viewchild("popup") popupElement : Elementref;

constructor(public modalService: NgbModalService) {}

showModal() {
   console.log("popupElement",this.popupElement);         // undefine
   this.modalService.open(this.popupElement,{...});
}

console in above child's function will be undefined if showModal() is called from parent on button click. If showModal() function will click from child component,then it will put log without any undefine.

我无法在其他任何地方移动 html 模板。

StackBlitz:https://stackblitz.com/edit/angular-multiple-component-th9dna?devtoolsheight=33&file=src/app/dy1.component.ts

可能是因为 @viewchild 无法在课外访问。 有没有这种代码可以访问孩子的 viewChild 引用? :

onButtonClick() {
   popupCompo.showModal.bind(popupCompo)
}

这样 showModal 将在子组件而不是父类的上下文中调用

如何从子组件显示模态,请指导我从父类调用方法时我可以为访问viewchild做什么。

解决方法

您必须再次使用 ViewChild

app.component.tsapp.component.html 中试试这个:

// assign reference variable to child element
<dy1 #child></dy1>
<button (click)="getchildP()">parent : get P</button>
......
@Component({
  selector: 'my-app',templateUrl: './app.component.html',styleUrls: ['./app.component.css']
})
export class AppComponent {
  compo1: any;
  demo = 'string';
  // get a handle on the child component
  @ViewChild('child') dy1Component: Dy1Component;
  constructor() {
    
  }
  ngOnInit() {}

  getchildP() {
    // use the reference
    this.dy1Component.getP();
  }
}

您的方法行不通,因为您正在创建子组件的新实例,而不是获取父组件在 HTML 中创建的实例的句柄。

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。