1

I'm populating an ng-content with some async values and I can see my content printed in the HTML but can't access to the ContentChildren from the component code.

// form.component.ts
@Component({
  template: `<dropdown>
          <option class="p-2" value="">Choose your Business</option>
          <option
            class="p-2"
            *ngFor="let business of businesses$ | async"
            [attr.value]="business.id">{{ business.name }}</option>
    </dropdown>`
  ...
})
class FormComponent {
  businesses$ = ...
}

// dropdown.component.ts
@Component({
  selector: 'dropdown',
  template: '<select><ng-content selector="option"></ng-content></select>',
  ...
})
class DropdownComponent implements AfterContentInit {
  @ContentChildren(HTMLOptionElement) options: QueryList<HTMLOptionElement>;

  ngAfterContentInit() {
    console.log(this.options.length); // it always returns 0
    this.options.changes.subscribe((changes) => {
      console.log('After Changes: ', changes.length); // this part is never executed
    });
  }
}

The select is printed with the options passed but the code never captures the options in the ContentChildren.

nicowernli
  • 3,250
  • 22
  • 37
  • Shouldn't it be `select="option"` instead of `selector="option"` ? – Andrei Gătej Apr 13 '20 at 14:35
  • yes it is that way, I'll edit the post – nicowernli Apr 13 '20 at 15:20
  • 1
    Does this answer your question? [How do I select a ContentChild of a native element in Angular 6?](https://stackoverflow.com/questions/51673978/how-do-i-select-a-contentchild-of-a-native-element-in-angular-6). You cannot use `HTMLOptionElement` in `@ContentChildren` – Shlang Apr 13 '20 at 18:40

0 Answers0