简体   繁体   English

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

[英]How to ask child component to access it's html template and show something on UI from parent component using component's class instance?

I am working on one project in which, I have 2 component :我正在做一个项目,其中有 2 个组件:

  1. Main component,主要成分,
  2. Popup component弹出组件

Main Component TS:主要组件 TS:

popupCompo = new popupComponent();

onButtonClick() {
   popupCompo.showModal();
}

popup Component TS :弹出组件 TS :

==> HTML ==> HTML

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

==> TS : ==> 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.

I can't move html template at any other places.我无法在任何其他地方移动 html 模板。

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

It might due to @viewchild can't access outside of class.这可能是由于@viewchild无法在课外访问。 Is there any this kind of code possible to access child's viewChild reference?有没有这种代码可以访问孩子的 viewChild 引用? :

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

So that showModal will call in a context of child component instead of parent class.这样 showModal 将在子组件而不是父类的上下文中调用。

How can I show modal from child component , Please guide me what Can I do for access viewchild when call method from parent class.如何从子组件显示模态,请指导我从父类调用方法时我可以为访问视子做什么。

You have to use ViewChild again.您必须再次使用ViewChild

Try this in app.component.ts and app.component.html :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();
  }
}

Your way doesn't work because you're creating a new instance of the child component and not grabbing a handle on the instance that your parent component creates in the HTML.您的方式不起作用,因为您正在创建子组件的新实例,而不是获取父组件在 HTML 中创建的实例的句柄。

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

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