Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Angular2 - ContentChild query does not find nested components

I am trying to set up an Angular2 component that automatically focuses an input element that is inserted via content projection.

The solution I am using is based off of this answer. I have an additional requirement that the input element might be nested inside another component. However, I am finding that the ContentChild query is not able to detect elements buried deep inside ng-content tags.

@Component({
  selector: 'inner-feature',
  template: "<input auto-focus>",
  directives: [AutoFocus]
})
export class InnerFeature { }

@Component({
  selector: 'feature',
  template: `
    <div [class.hide]="!show">
      <ng-content></ng-content>
    </div>
  `
})
export class Feature {
  @ContentChild(AutoFocus)
  private _autoFocus: AutoFocus;

  private _show: boolean = false;

  @Input()
  get show() {
    return this._show;
  }
  set show(show: boolean) {
    this._show = show;
    if (show && this._autoFocus) {
      setTimeout(() => this._autoFocus.focus());
    }
  }
}

@Component({
  selector: 'my-app',
  template: `
    <div>
      <button (click)="toggleFeature()">Toggle</button>
      <feature [show]="showFeature">
        <inner-feature></inner-feature>
      </feature>
    </div>
  `,
  directives: [Feature, InnerFeature]
})
export class App {
  showFeature: boolean = false;

  toggleFeature() {
    this.showFeature = !this.showFeature;
  }
}

The _autoFocus property never gets populated. Contrast that with the case where the auto-focus directive is not nested inside another component and it works fine. Is there a way to make this work?

(I have not pasted the code for AutoFocus since it's not crucial to this example.)

See Plunker for a demo.

UPDATED code above to fix a missing directive.

like image 392
mhusaini Avatar asked Jun 27 '16 17:06

mhusaini


1 Answers

Use ContentChildren with descendants set to true

@ContentChildren(AutoFocus, { descendants: true })
like image 127
kodebot Avatar answered Sep 30 '22 08:09

kodebot