[英]How to ask child component to access it's html template and show something on UI from parent component using component's class instance?
我正在做一个项目,其中有 2 个组件:
popupCompo = new popupComponent();
onButtonClick() {
popupCompo.showModal();
}
==> 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
。
在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();
}
}
您的方式不起作用,因为您正在创建子组件的新实例,而不是获取父组件在 HTML 中创建的实例的句柄。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.