- Retrieve information using the directive class token.
my-input.directive.ts
import { Directive } from '@angular/core';
@Directive({
selector: '[myInput]',
})
export class MyInputDirective {}
my-input-container.component.ts
import { Component, Input, ContentChild, AfterContentInit, ElementRef } from '@angular/core';
import { MyInputDirective } from './my-input.directive';
@Component({
selector: 'my-input-container',
template: `<ng-content></ng-content>`,
styles: [`h1 { font-family: Lato; }`]
})
export class MyInputContainerComponent implements AfterContentInit {
@ContentChild(MyInputDirective, { read: ElementRef }) child: MyInputDirective;
ngAfterContentInit() {
console.log(this.child);
}
}
usage:
<my-input-container>
<input myInput />
</my-input-container>
Live demonstration
- Access data through the template variable.
If you are only interested in the ElementRef, you can disregard the custom directive and query by the template variable instead.
my-input-container.ts
import { Component, Input, ContentChild, AfterContentInit, ElementRef } from '@angular/core';
@Component({
selector: 'my-input-container',
template: `<ng-content></ng-content>`,
styles: [`h1 { font-family: Lato; }`]
})
export class MyInputContainerComponent {
@ContentChild('myInput') child: ElementRef;
ngAfterContentInit() {
console.log(this.child);
}
}
usage:
<my-input-container>
<input #myInput />
</my-input-container>
Live demonstration
In general, the preferred choice is the first option as seen with @angular/material
and their input component. They pair the container component (mat-form-field
) with a directive applied to the native input element (matInput
).
This method offers more flexibility since you can query either for the Directive or for the ElementRef.
@ContentChild(MyInputDirective) child: MyInputDirective;
@ContentChild(MyInputDirective, { read: ElementRef }) child: MyInputDirective;