title: @Viewchild not initializing during ngOnInit
body: <p>I'm running two MatTables in different components with  data sources from different observables.  One of my tables sort functionality is working fine and but on my second table it seems as if the @ViewChild for MatSort doesn't initialize during ngOnInit.  </p>
  
  <p>Data renders and the material table has sort buttons but the functionality is nothing. Checked my imports and the module and everything is fine.<br>
  On logging the MatSort one component logs a MatSort object and the other is undefined</p>
  
  <p>Sorting not working.</p>
  
  <p>Feed.component:  </p>
  
  <pre><code>   import { PostService } from './../../services/post.service';
     import { Post } from './../../models/post';
     import { Component, OnInit, ViewChild, ChangeDetectorRef} from 
       '@angular/core';
     import { MatSort, MatTableDataSource, MatCheckbox, MatPaginator, 
       MatTabChangeEvent, MatDialog, MatDialogActions, MatTable}  from 
     "@angular/material"
  
  
  
  export class FeedComponent implements OnInit {
    @ViewChild(MatSort) sort: MatSort;
    @ViewChild(MatPaginator) paginator: MatPaginator;
    postData: Post[] =[];
    dataSource : MatTableDataSource&lt;any&gt; 
    currentUser = JSON.parse(localStorage.getItem('user'))
    displayedColumns:string[] = ['User','Title', "Description", 
    "Contact" ]
    posts = this.ps.getPosts();
  
    constructor(private ps: PostService, public dialog:MatDialog, 
      public change:ChangeDetectorRef, public ms:MessageService) { 
  
    }
  
  
  
  refreshPosts(){
     console.log(this.sort) &lt; -------comes back undefined
    this.posts.subscribe(posts=&gt;{
      this.dataSource.sort = this.sort
       this.postData = posts.filter(post =&gt; post.uid != 
         `${this.currentUser.uid}` &amp;&amp; post.claimedBy 
          !=`${this.currentUser.uid}`);
       this.dataSource= new MatTableDataSource(this.postData)
       this.dataSource.paginator = this.paginator;
      });
  
    }
  ngOnInit() {
     this.refreshPosts()
     console.log(this.sort)
     }
  
  
  Post.service
    getPosts(){
      return  this.afs.collection('posts').snapshotChanges()
       .pipe(map(actions =&gt; 
       actions.map(this.documentToDomainObject)))
    }
   documentToDomainObject = _ =&gt; {
    const object = _.payload.doc.data();
    object.id = _.payload.doc.id;
    return object;
  }
  </code></pre>
  
  <p>Now my next component initializes in the same way but the @ViewChild shows up as a MatSort Object</p>
  
  <p>Message.component:</p>
  
  <pre><code>export class MessageComponent implements OnInit {
  
  
   @ViewChild(MatSort) sort: MatSort;
    userReceived: MatTableDataSource&lt;any&gt;;
    userSent: MatTableDataSource&lt;any&gt;;
    displayedColumns:string[] = ["createdAt",'author',"title", "Delete"]
    sentColumns:string[] = ["createdAt","recipient", "title", "Delete"]
  
  
    currentUserId= this.currentUser['uid']
    currentUsername = this.currentUser['displayName']
    recipient:any;
    selectedMessage: MatTableDataSource&lt;Message&gt;;
    messageColumns= ['From','Title',"Body"];
  
  
  
  
    constructor(public ms:MessageService, public change:ChangeDetectorRef, public dialog: MatDialog  ) { }
  
    ngOnInit() {
      console.log(this.sort)
      this.updateMessages()
      this.currentUserId = this.currentUserId;
      this.currentUsername = this.currentUsername;
  
   }
  
  
  updateMessages(){
      this.ms.getUserSent().subscribe(messages =&gt; {
        console.log(this.sort) &lt;------logs MatSort object
        this.userSent = new MatTableDataSource(messages)
        this.userSent.sort = this.sort
        console.log(this.userSent.sort)
        console.log(this.userSent.data)
  
      })
  </code></pre>
  
  <p>message.service </p>
  
  <pre><code> getUserSent() {
      let messages:any[] = [];
      this.userSent = this.afs
        .collection('messages', ref =&gt; ref.where('uid', '==', `${this.currentUser.uid}`)).snapshotChanges() 
  return this.userSent
    }
  </code></pre>
  
  <p>feed.component.html</p>
  
  <pre><code>&lt;div class = "mat-elevation-z8"&gt;
      &lt;mat-form-field&gt;
          &lt;input matInput (keyup)="applyFilter($event.target.value)" placeholder="Search Posts"&gt;
        &lt;/mat-form-field&gt;
    &lt;table matSort mat-table [dataSource]="dataSource" style="text-align:left"&gt;
        &lt;ng-container matColumnDef="User"&gt;
            &lt;th mat-header-cell *matHeaderCellDef mat-sort-header&gt;User&lt;/th&gt;
            &lt;td mat-cell *matCellDef="let post"&gt;{{post.displayName}}&lt;/td&gt;
         &lt;/ng-container&gt;
  
    &lt;ng-container matColumnDef="Title"&gt;
      &lt;th mat-header-cell *matHeaderCellDef&gt;Title&lt;/th&gt;
      &lt;td mat-cell *matCellDef="let post"&gt;{{post.title | truncate:15:false }}&lt;/td&gt;
   &lt;/ng-container&gt;
  
    &lt;ng-container matColumnDef="Description"&gt;
      &lt;th mat-header-cell *matHeaderCellDef &gt;Description&lt;/th&gt;
      &lt;td mat-cell *matCellDef="let post"&gt;{{post.description | truncate: 20 : false}}&lt;/td&gt;
    &lt;/ng-container&gt;
  
  
  
  
  
    &lt;ng-container matColumnDef="Contact"&gt;
      &lt;th mat-header-cell *matHeaderCellDef&gt; Contact &lt;/th&gt;
      &lt;td mat-cell *matCellDef="let post"&gt;
        &lt;button  id="{{post.id}}" color="primary" (click)="openDialog($event.target.id)" style = "outline:none" value={{post.id}}&gt;Claim&lt;/button&gt;
      &lt;/td&gt;
  
    &lt;/ng-container&gt;
  
    &lt;tr mat-header-row *matHeaderRowDef="displayedColumns"&gt;&lt;/tr&gt;
    &lt;tr mat-row *matRowDef='let row; columns: displayedColumns'&gt;&lt;/tr&gt;
  &lt;/table&gt;
  &lt;/div&gt;
    &lt;mat-paginator [length]="this.postData.length" [pageSize]="5" [pageSizeOptions]="[5,10,25]"&gt;&lt;/mat-paginator&gt;
  </code></pre>
  
  <p>I really cant find why in my first component the sort returns undefined when in my second, working component it returns and object.  Am I missing something about the order of @ViewChild?</p>