5
votes

Im working on a component and i'd like to implement a function that focus's the first input element inside it's ng-content.

So i tried rougly this he following template code and attempted to use ViewChildren and ContentChildren.

@Component({
  selector: '[my-component]', // tslint:disable-line
  template: `<div class="my-container">
        <ng-content></ng-content>
      </div>`
})
export class MyComponent implements AfterViewInit, OnDestroy {

  @ViewChildren('input') vc;
  @ContentChildren('input', {descendants: true}) cc;

  ngAfterViewInit() {
    //Nothing in either QueryList ???
    console.log(this.vc, this.cc);
  }

  focus () {
    //Nothing in either QueryList ???
    this.vc.first.nativeElement.focus();
  }
}

When use the component in a template/page it then looks roughly like this:

<div my-component>
  <div class="field"><input></div>
  <div class="field"><input></div>
  <div class="field"><input></div>
  <div class="field"><input></div>
  <div class="field"><input></div>
</div>

So again, what i would like is to get all of the input elements that appear in the content and and they could also be buried be in divs and wrappers. It seems like ContentChildren should be correct but it is not returning me any elements. i.e. QueryList.results is empty.

What am i doing wrong or how can i get the inputs inside the content area?

1

1 Answers

9
votes

The @ViewChildren decorator supports both directive or component types as parameter. Supports also the name of a template variable, meaning the #ref definition. So I believe it would work if you put for instance

<div my-component>
  <div class="field"><input #myInput></div>
  <div class="field"><input #myInput></div>
  <div class="field"><input #myInput></div>
  <div class="field"><input #myInput></div>
  <div class="field"><input #myInput></div>
</div>

And then

@ViewChildren('myInput') vc;