I've been googling around, and am still a bit new to angular 5/6, but I'm trying to see if something is possible.
Problem
Say I have a template:
<ng-template #rt let-r="result" let-t="term">
<ngb-highlight [result]="r.typeAheadDisplayName" [term]="t" ></ngb-highlight>
<span *ngIf="r.primaryName ">(alias for {{ r.primaryName }}) </span>{{ r.metaData }}
</ng-template>
Within this template a button will generate that can be used as a means of chosing an option. However, for a given reason I need to be able to target :first-child
of the array of buttons.
I know that I can select the element/template doing:
@ViewChild('rt') rt : TemplateRef<any>;
but, can I actually do a function similar to jQuery's .find
or even the same in AngularJS, to target the elements that would be found inside of this template. I've been googling and can't see to find an answer.
Add a template reference variable to the component HTML element. Import @ViewChild decorator from @angular/core in component ts file. Use ViewChild decorator to access template reference variable inside the component.
We use the ViewChild to get the ElementRef of an HTML element in the component class. Angular also inject ElementRef of the Host element of the component or directive when you request for it in the constructor.
You can get a handle to the DOM element via ElementRef by injecting it into your component's constructor: constructor(private myElement: ElementRef) { ... }
TemplateReflink Represents an embedded template that can be used to instantiate embedded views. To instantiate embedded views based on a template, use the ViewContainerRef method createEmbeddedView() .
nativeElement
is what you're looking for. It will give you the native DOM node, and from that you can use methods like querySelector
to query child nodes.
@Component()
export class MyComponent implements OnInit {
@ViewChild('rt') rt : ElementRef;
ngOnInit() {
const childNode = this.rt.nativeElement.querySelector('.child-class');
}
}
Update:
For using ng-template
, you can use ContentChild
and TemplateRef
together. TemplateRef
still has an embedded ElementRef
within it, so you will still be able to access the nativeElement
property and do whatever querying you want.
<ng-template [ngTemplateOutlet]="rt"></ng-template>
@Component({selector: 'my-component'})
export class MyComponent implements OnInit {
@ContentChild('rt') rt: TemplateRef<any>;
ngOnInit() {
const childNode = this.rt.elementRef.nativeElement.querySelector('.foo');
}
}
Now you can use that component like so:
<my-component>
<ng-template #rt>
<div class="foo">Hello world</div>
</ng-template>
</my-component>
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With