Reputation: 2599
I have a custom component that is a <h1>
tag and an <input>
tag. I want be be able to access the input from my custom directive however when I try to use Angular's @ContentChild
attribute, it is always undefined
.
If I apply my custom directive to a native <input>
, it works fine.
I have set up a StackBlitz highlighting this issue here: https://stackblitz.com/edit/using-contentchild-in-directive
If you open the JavaScript console after the page has loaded, you will see:
Native Component: ElementRef {nativeElement: input}
Custom Component: undefined
How can I access the <input>
within the custom component from the directive?
Upvotes: 1
Views: 423
Reputation: 3862
Well this behavior is because you are accessing contentChild
with Template Reference Variable
called control
:
@ContentChild('control',null) public ctrlByName: any;
and it is only assigned to input
element:
<input #control name="Native Component" testDirective />
thats why test-component
is not being detected by ContentChild
so you can actually assign el
from ElementRef
to your element and it will work fine, you wont need ContentChild
:
constructor(private el: ElementRef) {
this.name = el.nativeElement.attributes.name.value;
this.ctrlByName = el;
}
Upvotes: 1