#104396
admin
Keymaster

Hi,

The thing is that the add new tab button adds an empty tab. It does not add a new tab with the template structure you added in the template i.e the new tab does not have ng-container in it. For that purpose we can use ng-template. Please, take a look at the updated code below

import { Component, AfterViewInit, ViewChildren, QueryList, ViewChild, ComponentRef, ChangeDetectorRef, ViewContainerRef } from '@angular/core';
import { TabItem, TabItemComponent, TabsComponent } from 'smart-webcomponents-angular/tabs';
import { ThingComponent } from './thing.component';
import { ViewRefAnchorDirective } from './view-ref-anchor.directive';

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

  // I am expecting this list to be updated when new tabs are added.
  smartItems: TabItem[] = [];

  @ViewChildren(ViewRefAnchorDirective) anchors = new QueryList();

  @ViewChild('tabs', {read: TabsComponent, static: false}) tabs!: TabsComponent;
  @ViewChild('dynamic', { read: ViewContainerRef })

  viewRef!: ViewContainerRef;

  numTabs = 0;

  ngAfterViewInit(): void {
    this.tabs.getTabs().then(tabs => {
      this.numTabs = tabs.length;
    });

    this.anchors.forEach(tab => this.loadComponent(tab as any));
 	this.smartItems = Array.from(document.querySelectorAll('smart-tab-item'));
	 }

  onAddNewTabClick(event: Event) {
    this.tabs.getTabs().then(tabs => {
      this.numTabs = tabs.length;

      	// create a new dynamic component.
		const container = document.createElement('div');
		const componentRef: ComponentRef<ThingComponent> =  this.viewRef.createComponent(ThingComponent);
	
		// dynamically add the component to a new container host element.
		container.appendChild(componentRef.location.nativeElement);
		// update tabs.
		this.tabs.update(tabs.length-1, 'Updated Tab', container);
		
		
		this.smartItems = Array.from(document.querySelectorAll('smart-tab-item'));
					
    });
  }

  loadComponent(viewRefAnchor: ViewRefAnchorDirective) {
    viewRefAnchor.viewContainerRef.clear();
    return viewRefAnchor.viewContainerRef.createComponent(ThingComponent);
  }
}

Hope this helps.

Regards,
Peter