[英]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 个组件:
popupCompo = new popupComponent();
onButtonClick() {
popupCompo.showModal();
}
==> 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
@viewchild
can't access outside of class.@viewchild
无法在课外访问。 Is there any this kind of code possible to access child's viewChild reference?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.ts
和app.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.