Solvedcomponents When using @ViewChild element.nativeElement is undefined

Bug, feature request, or proposal:

Bug

What is the expected behavior?

@ViewChild element.nativeElement has value

What is the current behavior?

@ViewChild element.nativeElement is undefined

@Component({
  selector: 'material-app',
  template:`
  <button #button md-raised-button>button</button>
  `
  
})
export class AppComponent {
  @ViewChild('button') button;
  ngAfterViewInit(){
    console.log(this.button);
    console.log(this.button.nativeElement); //undefined
    console.log(this.button.nativeElement.value); // obviously error here
  }

What are the steps to reproduce?

http://plnkr.co/edit/gSEsELlTAbrqvOOduSdr?p=preview

What is the use-case or motivation for changing an existing behavior?

Need to access to an element with @ViewChild

Which versions of Angular, Material, OS, browsers are affected?

Angular 4.0.1
Material beta.2
All browsers

Is there anything else we should know?

If you take out the md-raised-button from the button then this.button.nativeElement will work.

14 Answers

✔️Accepted Answer

@gouldina Please refer to the link that @willshowell posted above. Basically, just do
@ViewChild('nameForMaterialElement', {read: ElementRef}) private nameForMaterialElement: ElementRef;

The reason is that md-radio-button is an angular component (which itself is a directive) and ViewChild returns the whole component if you do not specify the read option

Other Answers:

As a workaround for now, you can define Child like this

@ViewChild('sidenavContainer') private sidenavContainer: any; and then call

this.sidenavContainer._element.nativeElement

For anyone wondering.

Related Issues:

885
components Error: mat-form-field must contain a MatFormFieldControl.
You have to add to app.module.ts: Bug feature request or proposal: When doing a karma/jasmine test I...
160
components [Table] Add example with dynamic columns
For those interested Bug feature request ...
111
components [Table] Throw error if MatSortModule is not imported while using "MatSort/matSort"
In came here because I hit the error @tzachs reported above: In my case the issues was that by accid...
100
components Can't drag md-slider
The import order solution never worked for me though it does seem to be related to something overrid...
96
components animation trigger "transformMenu" has failed to build
Sorry for commenting on a closed issue but got the same error when upgrading to Angular 5 using JEST...
87
components When using @ViewChild element.nativeElement is undefined
@gouldina Please refer to the link that @willshowell posted above Basically just do @ViewChild('name...
81
components Fixed header rows for md-table
to simplify above solution Write Bug feature request ...
76
components form-field: remove extra bottom space
10px is not enough considering size of padding <mat-form-field style= margin-bottom: -1.25em> I agre...
71
components Angular CLI + Angular Material {MatButtonModule} breaks angular build
Open your package.json file just change these to whatever the current version of the other angular c...
66
components strictTemplates, Angular 9: compability with Ivy
Dunno if it helps Enabling the new strictTemplates flag in Angular 9's compiler options generates th...
66
components [Table] - Add example with multiple filtering columns
@erickyi2006 I am using mat-menu mat-select mat-input everywhere to meet my requirements for the mat...
63
components NullInjectorError: No provider for MatDialogRef!
@jepetko Thanks for that worked I also had this in my dialog component constructor: @Inject(MAT_DIAL...
53
components No provider for MatDialogRef!
You will get that exact No provider for MatDialogRef error in case you include your dialog's compone...
41
components Opening MdDialog in ngOnInit throws ExpressionChangedAfterItHasBeenCheckedError
I had the same problem here when I tried open the MatDialog: ExpressionChangedAfterItHasBeenCheckedE...
41
components MdPaginatorIntl Internationalization example
@mhosman @rsaulo This is how I did it in @angular/material: ^5.0.3 Create separate file e.g ...
38
components Mat-tooltip bug: The pipe 'async' could not be found
Setting enableIvy: false (or simply removing it) in angularCompilerOptions (tsconfig.json) resolved ...
37
components Cannot find module... Problems with cdk
Did you install @angular/cdk? Bug feature request ...
36
components matTable - DataSource issue
@teoCasasbuenas @pablitodeveloper change: to If you're using version 5.2.4 of @angular/material http...
34
components Can't bind to 'ngModel' since it isn't a known property of 'md-input'.
You probably need to import the FormsModule in you app.module. I've seen some similar issues of peop...
33
components proposal: the current and the future state of material2
I agree we could definitely be more clear about the current status of the project For the most part ...
33
components Default sorting in Sort header
You're mistaking matSortStart for matSortDirection Question: How can I change Angular Material code ...
28
components Error Setting Up Custom Material Theme in Angular-CLI Project
Had the same issue with CLI: 1.6.4 node: 9.2.0 Angular: 5.0.0 Material: 5.0.4 just need to remove th...
25
components MatTable: Cannot read property 'nativeElement' of undefined
Well nevermind I found the issue Somehow my target property in tsconfig.json had the value of 'es201...
23
components Plunkers not working for md-data-table examples
Adding import { CdkTableModule } from '@angular/cdk'; to main.ts and add CdkTableModule to the impor...
23
components Does not package with ng-packagr
@willshowell adding material to lib.externals in ng-package.json: seems to have fixed my issue my li...
22
components [feature] Improve datepicker documentation for date format
@Robouste Right now you have to write your own DateAdapter. That is the only workaround that I found...
22
components Illegal state: Could not load the summary for directive ObserveContent
OK after numerous hours working on a reproduction and then changing code/config one at a time and re...
22
components [Table] Ability to filter complex objects
Sounds like you want a custom filter function which you can do by overriding the filterPredicate ...
21
components No documentation exists for Jasmine unit tests of Angular components containing @angular/material
I can add some of the things I've come across which might help out others looking for info Hopefully...
20
components Error: StaticInjectorError[BreakpointObserver] No provider for BreakpointObserver
my fail I tried: import {MatSnackBarModule} from @angular/material/snack-bar; but I have to: import ...
19
components feat(stepper): support lazy rendering of steps
Not sure if I am just stating the obvious Bug feature request ...
19
components Can't bind to 'mdMenuTriggerFor' since it isn't a known property of 'button'
I am getting the same error when running tests Bug feature request ...
18
components mat-table: Rows and table elements widths don't grow according to cell widths
The following workaround worked perfectly for me Bug feature request or proposal: Bug ...
17
components Cannot customize style of md-tabs
You need to use /deep/: Bug feature request ...
17
components Not able to compile custom theme
Looks like they've changed the Github build of Material I'm not able to set the custom material them...
17
components Theming your own component doc incorrectly references pre-built theme
Thank you all to the contributions to this thread after fighting with the docs this was a very usefu...
17
components [Paginator] Unclear in docs about how to set language
//Atribute @ViewChild(MatPaginator) paginator: MatPaginator; ngOnInit(){ .. Bug feature request or p...
16
components Add documentation for MomentDateAdapter usage
Full process for using Moment objects instead of Date objects npm i @angular/material-moment-adapter...
16
components Getting "No component factory" error while opening a Material Dialog in lazy loaded Component
You need to import MatDialogModule in ConsumerModule in order for it to know about the entryComponen...
16
components Weird ripple effect
I have got the same problem Each click of the bottom inserts a Into my html and it keeps stacking an...
15
components Slide Toggle Doesn't Seem to be working in Alpha 7 Error: Cannot find name 'HammerInput'
For those finding this issue that have a similar configuration to mine: angular-material: 2.0.0-alph...
14
components Add guidance for styling invalid inputs
For the time being I'm using a md-hint to show my error messages: It might help someone ...
14
components Add Customize Css Class to the Mat-Tab-Content and other Mat-X tags which are generated runtime
Why is this closed? <mat-tab> classes are not applied anywhere Bug feature request ...
13
components Snackbar + md-icon
Use a custom snackbar component: customsnackbar.component.ts: app.component.ts: app.module.ts: ...
13
components [Table] simpler example without example database
Anyway it would be possible to design a table completely in HTML Without data source binding Like: O...
13
components Md-expansion panel opened and close events not firing on prod build (beta.11)
Thanks @josephperrott If you're like me and just upgraded your project and even ran the md -> mat up...
12
components Custom Theme issue
Your $primary $accent etc are not what the theme function is expecting If you look at our pre-built ...
12
components [MdSidenav] - Sidenav Resizing Regression
Here is my solution: HTML TS Bug feature request or proposal: Bug/Regression from 2.0.0-beta.8 ...
12
components Docs bug: How to add rows to table
MatTableDataSource does not have the renderRows method It's in CdkTable | MatTable However in Angula...
11
components (suggestion)md-table with http example
Hey @lemang Here is my code 👨‍💻 Bug feature request ...