I am trying to add ng-select & ng-option in typescript (angular). But I am not sure if that is possible since ng-select is a component which is not rendered. How can I make this work?
@Component({
selector: 'app-testing',
templateUrl: './app-testing.component.html',
styleUrls: ['./app-testing.component.scss']
})
export class TestCompontnt implements OnInit {
ngOnInit() {}
example(type: string) {
return `
<table class="table table-striped table-bordered table-hover table-checkable middle-align-table">
<thead>
<tr>
<th style="width: 40%">TT</th>
<th>TT2</th>
</tr>
</thead>
<tbody>
<td>okej</td>
<td>
<div class="input-group">
<input type="number" class="form-control">
<div class="input-group-append">
<ng-select>
<ng-option value="TEST">TEST</ng-option>
</ng-select>
</div>
</div>
</td>
</tbody>
</table>
`;
}
}
I tried to add dropdown menu to dynamic component.
1
If you want to apply your template via innerHTML
, you cannot use Angular components such as <ng-select>
. Instead you need to use the native select
and option
elements from HTML.
<select>
<option value="TEST">TEST</option>
</select>
If you want to use Angular components, you need to add the template to the <component-name>.component.html
file, and not as string in your TypeScript code. See https://angular.dev/essentials/rendering-dynamic-templates
If you want to programmatically render an Angular component, please see https://angular.dev/guide/components/programmatic-rendering
4
You can use ng-template
then pass the context as this
and then finally render using ng-container
import { Component } from '@angular/core';
import { CommonModule } from '@angular/common';
import { FormsModule } from '@angular/forms';
import { bootstrapApplication } from '@angular/platform-browser';
import 'zone.js';
import { NgSelectModule } from '@ng-select/ng-select';
@Component({
selector: 'app-root',
standalone: true,
imports: [NgSelectModule, FormsModule, CommonModule],
template: `
<ng-container *ngTemplateOutlet="select; context: {that: this}"></ng-container>
<ng-template #select let-that="that">
<table class="table table-striped table-bordered table-hover table-checkable middle-align-table">
<thead>
<tr>
<th style="width: 40%">TT</th>
<th>TT2</th>
</tr>
</thead>
<tbody>
<td>okej</td>
<td>
<div class="input-group">
<input type="number" class="form-control">
<div class="input-group-append">
<ng-select [(ngModel)]="that.selected">
<ng-option value="TEST">TEST</ng-option>
</ng-select>
</div>
</div>
</td>
</tbody>
</table>
</ng-template>
{{selected}}
`,
})
export class App {
name = 'Angular';
selected = '';
}
bootstrapApplication(App);
Stackblitz Demo