最新消息:雨落星辰是一个专注网站SEO优化、网站SEO诊断、搜索引擎研究、网络营销推广、网站策划运营及站长类的自媒体原创博客

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

programmeradmin0浏览0评论

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?

发布评论

评论列表(0)

  1. 暂无评论