patterntypescriptangularCritical
Access template reference variables from component class
Viewed 0 times
variablesaccessfromcomponentclasstemplatereference
Problem
Is it possible to access the template access variable from the component class?
i.e., can I access it here,
class XComponent{
somefunction(){
//Can I access #ipt here?
}
}Solution
That is a use-case for
https://angular.io/docs/ts/latest/api/core/index/ViewChild-decorator.html
Here's a working demo:
https://stackblitz.com/edit/angular-viewchilddemo?file=src%2Fapp%2Fapp.component.ts
update demo using angular v18:
https://stackblitz.com/edit/angular-v18-viewchild?file=src%2Fmain.ts
which also considers the new signal way of using ViewChildren: https://angular.dev/api/core/viewChild?tab=usage-notes
@ViewChild:https://angular.io/docs/ts/latest/api/core/index/ViewChild-decorator.html
class XComponent {
@ViewChild('ipt', { static: true }) input: ElementRef;
ngAfterViewInit() {
// this.input is NOW valid !!
}
somefunction() {
this.input.nativeElement......
}
}Here's a working demo:
https://stackblitz.com/edit/angular-viewchilddemo?file=src%2Fapp%2Fapp.component.ts
update demo using angular v18:
https://stackblitz.com/edit/angular-v18-viewchild?file=src%2Fmain.ts
which also considers the new signal way of using ViewChildren: https://angular.dev/api/core/viewChild?tab=usage-notes
Code Snippets
class XComponent {
@ViewChild('ipt', { static: true }) input: ElementRef;
ngAfterViewInit() {
// this.input is NOW valid !!
}
somefunction() {
this.input.nativeElement......
}
}Context
Stack Overflow Q#39631594, score: 210
Revisions (0)
No revisions yet.