Rae-Win
Rae-Win

Reputation: 9

access Template Reference variable within ng-template

I am using '@ng-bootstrap/ng-bootstrap' in my Angular project.

I have a modal which template reference variable is content and inside that modal template I have another template variable oppGrid. I want to access the elementRef for oppGrid but i am facing problems, it seems to be null. Even when i tried using ngAfterContentInit() and ngAfterViewInit(). So how do i access & do DOM manipulation in #oppGrid, a template reference variable within an ng-template?

//app.component.html code 
<ng-template #content let-modal>
  <div class="modal-header">
    <h4 class="modal-title" id="modal-basic-title">Profile update</h4>
    <button type="button" class="close" aria-label="Close" (click)="modal.dismiss('Cross click')">
      <span aria-hidden="true">&times;</span>
    </button>
  </div>
  <div class="modal-body p-0 m-0">
    <div class="container p-0 m-0">
      <div class="row p-0 m-0 justify-content-center">
        <div #oppGrid class="col-lg-6 p-0 m-0 border border-primary">
          HELLO WORLD 1
        </div>
      </div>
      
    </div>
  </div>
  <div class="modal-footer">
    <button type="button" class="btn btn-outline-dark" (click)="modal.close('Save click')">CLOSE</button>
  </div>
</ng-template>

//app.component.ts
import { Component,ElementRef,  ViewChild, AfterViewInit, ContentChild, AfterContentInit} from '@angular/core';
import {NgbModal, NgbModalRef} from '@ng-bootstrap/ng-bootstrap';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})

export class AppComponent implements AfterViewInit, AfterContentInit{
  modalRef:NgbModalRef;
  @ViewChild("content") gameModal:ElementRef;
  @ContentChild('oppGrid') oppGrid: ElementRef;

   constructor(private modalService: NgbModal){
   }
   
   ngAfterViewInit(){
    this.modalRef = this.modalService.open(this.gameModal,{size:"xl"});
    console.log(this.gameModal);//works
    this.modalRef.shown.subscribe(()=>{
        console.log(this.oppGrid);//undefined
    });
      
    console.log(this.oppGrid);//undefined
   }
  ngAfterContentInit(){
    console.log(this.oppGrid);//undefined
  }
}

I've also tried with oppGrid being @ViewChild instead


...
@ViewChild('oppGrid') oppGrid: ElementRef;
....
ngAfterViewInit(){
    console.log(this.gameModal);//works
    console.log(this.oppGrid);//undefined
   }

Upvotes: 0

Views: 1295

Answers (1)

Rae-Win
Rae-Win

Reputation: 9

Actually the answer was in the docs all these while https://stackblitz.com/run?file=src%2Fapp%2Fmodal-component.ts.

Basically create a new component which handles the Modal. Then within that component use @ViewChild as per normal to access those HTMLEntities.

Upvotes: 0

Related Questions