how to get ng-content and change it before rendering?

Discussão em 'Angular' iniciado por Ricardo Silva, Fevereiro 5, 2025.

  1. I was trying get a select that is passed to a component and strip the option out, then add an extra option. So far, the only way I was able to do it was by using renderer2 to explicitly add a new node before the other options.

    @Component({
    standalone: true,
    template: `
    <ng-content select="select">
    <!-- I wanted to prepend the option declaratively here -->
    <!-- <option value="">Some prepended option</option> -->
    <ng-template>
    <!-- either place the rest via template or content not that important -->
    </ng-template>
    </ng-content>
    `,
    selector: "cp-select",
    })
    export class SelectComponent implements OnInit {

    constructor(private el: ElementRef, private renderer: Renderer2) {}

    ngOnInit() {
    const select = this.el.nativeElement.querySelector("select option");
    if (select) {
    const option = this.renderer.createElement("option");
    this.renderer.setAttribute(option, "value", "");
    const text = this.renderer.createText("Prepend Option");
    this.renderer.appendChild(option, text);
    this.renderer.insertBefore(select.parentNode, option, select);
    this.renderer.setProperty(select, "selected", 0);
    }
    }
    }


    usage:

    <cp-select>
    <select>
    <option value="1">Option 1</option>
    </select>
    </cp-select>


    Before you give me alternatives, it is not what I am looking for. The point here is to learn and know if this is achievable without renderer, in a declarative way. I know I can use a template on the usage part and that way I would have access to it, but it is not what I am looking to answer.

    So, the question is it possible to get the options within cp-select extract it before it is rendered and from the template add an option before the other, all that before rendering the component?

    Continue reading...

Compartilhe esta Página