I am trying to create a custom reusable component based on material angular.
I have the following code dropdown.component.ts
import {AfterContentInit, Component, ContentChildren, QueryList, ViewChildren} from '@angular/core';
import {MatSelectModule} from "@angular/material/select";
import {MyOptionComponent} from "./dropdown-options.component";
@Component({
selector: 'app-dropdown',
standalone: true,
imports: [
MatSelectModule,
MyOptionComponent
],
template: `<mat-select><ng-content></ng-content></mat-select>`,
styleUrl: './dropdown.component.scss'
})
export class DropdownComponent implements AfterContentInit {
ngAfterContentInit(): void {
console.warn('AfterContentInit', this.children);
}
@ContentChildren(MyOptionComponent) children!: QueryList<MyOptionComponent>;
}
dropdown
dropdown-options.component.ts
import { Component, Input } from '@angular/core';
@Component({
selector: 'my-option',
standalone: true,
template: `<option value="{{value}}">{{label}}</option>`,
})
export class MyOptionComponent {
@Input() label: string = ''; // Display text
@Input() value: any; // Value for the dropdown
}
then I try to use it with:
<app-dropdown>
<my-option label="test" value="1" ></my-option>
<my-option label="test" value="1" ></my-option>
<my-option label="test" value="1" ></my-option>
</app-dropdown>
The console.warn('AfterContentInit', this.children);
brings back the child elements, but they never show in the DOM
Anyone have any idea what I’m missing?
1
did you check console on possible errors? If there is no errors, other possible reason of not rendering is ChangeDetection strategy such as onPush, you need change it to onDefault or use markForCheck() method in a place when you need rendering
import { Component, ChangeDetectorRef } from '@angular/core';
@Component({
selector: 'app-example',
template: `
<p>Count: {{ count }}</p>
<button (click)="increment()">Increment</button>
`,
changeDetection: ChangeDetectionStrategy.OnPush
})
export class ExampleComponent {
count = 0;
constructor(private cdr: ChangeDetectorRef) {}
increment() {
this.count++;
// Manually trigger change detection
this.cdr.markForCheck();
}
}
Check your imports if parent component(comoponent whose html you shared) has imported dropdown component in imports.
check the ts file of the parent component, look for missing import there, for this component, if everything looks fine but still not working, show me the parent component where you are using this dropdown ts and htlm also the routes file for the module the parent component is a part of.