In ngAfterViewInit() find the element (s) of interest, then be sure to add event listeners. The code below assumes only one input:
@Component({ selector: 'textbox', template: `<h3>textbox value: {{inputValue}}</h3> <div class="textbox-wrapper"> <ng-content></ng-content> </div>`, }) export class TextboxComp { inputValue:string; removeListenerFunc: Function; constructor(private _elRef:ElementRef, private _renderer:Renderer) {} ngAfterContentInit() { let inputElement = this._elRef.nativeElement.querySelector('input'); this.removeListenerFunc = this._renderer.listen( inputElement, 'input', event => this.inputValue = event.target.value) } ngOnDestroy() { this.removeListenerFunc(); } }
Plunker
This answer is essentially an imperative approach, in contrast to Gunther's declarative approach. This approach might be easier to expand if you have multiple inputs.
It seems that there is no way to use @ContentChild() (or @ContentChildren() ) to search for DOM elements in a user template (i.e. ng content content) ... something like @ContentChild(input) does not seem to exist. Therefore, I use querySelector() .
In this blog post http://angularjs.blogspot.co.at/2016/04/5-rookie-mistakes-to-avoid-with-angular.html , Kara suggests defining a directive (e.g. InputItem) using the input selector and then use @ContentChildren(InputItem) inputs: QueryList<InputItem>; . Then we do not need to use querySelector() . However, I don't particularly like this approach, because the TextboxComponent user must somehow also know that the InputItem is in the directives array (I think some kind of component documentation might solve the problem, but I'm still not a fan) Here is the plunker for this approach.
source share