简体   繁体   中英

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 :

  1. Main component,
  2. Popup component

Main Component TS:

popupCompo = new popupComponent();

onButtonClick() {
   popupCompo.showModal();
}

popup Component 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.

I can't move html template at any other places.

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. 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.

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.

Try this in app.component.ts and 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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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