@Viewchild看不到matSort

时间:2018-03-16 00:50:04

标签: angular typescript datatables material-design viewchild

在我的Angular应用程序中,我的@ViewChild实例无法填充HTL matSort。

mycomponent.ts:

import { MatSort } from '@angular/material';

export class MyClassComponent {
     @ViewChild(MatSort) sort: MatSort;

}

ngOnInit() {
    console.log(this.sort); // undefined
}

mycomponent.html:

<mat-table #table [dataSource]="dataSource" matSort>
           .......................................................
           .......................................................

</mat-table>

我需要使用matSort中的sortChange,但它总是返回undefined。

4 个答案:

答案 0 :(得分:3)

您可能已经在课程级别导入了:

import { MatSort, MatTableDataSource } from '@angular/material';

这使得.ts类中的MatSort和MatTableDataSource类型可用。但是,您也尝试在组件的.html文件中使用相关模块作为指令,为此您的app.module.ts需要导入它们,我使用单独的NgModule来导入所有材料组件我使用ie

material\material.module.ts

import { NgModule } from '@angular/core';

import {
  MatTableModule,
  MatSortModule, 
} from '@angular/material';

@NgModule({
  imports: [
      MatTableModule,
      MatSortModule, 
    ],
  exports: [
      MatTableModule,
      MatSortModule, 
    ]
})
export class MaterialModule { }

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { HttpClientModule } from '@angular/common/http';

import { MaterialModule } from './material/material.module';
import { AppComponent } from './app.component';
import { myComponent } from './my/my.component';

@NgModule({
  declarations: [
    AppComponent,
    MyComponent
  ],
  imports: [
    BrowserModule,
    MaterialModule,
    BrowserAnimationsModule,
    HttpClientModule,
  ],
  providers: [],
  bootstrap: [AppComponent]
})
export class AppModule { }

答案 1 :(得分:1)

它将在AfterViewInit生命周期钩子中初始化并可用:

export class MyClassComponent implements AfterViewInit {
  @ViewChild(MatSort) sort: MatSort;

  ngAfterViewInit() {
    console.log(this.sort); // MatSort{}
  }
}

有关生命周期钩子的更多信息,请访问:https://angular.io/guide/lifecycle-hooks

答案 2 :(得分:1)

我正在使用angular 7,为我解决了这个问题的方法是在 app.modules.ts 中添加 MatSortModule 。我得到的错误是这里提到的错误。没有迹象表明缺少MatSortModule。

原始答案在这里: Angular 5 - Missing MatSortModule

答案 3 :(得分:1)

在Angular 8中,我不得不使用setter和可选参数static = false:

   @ViewChild(MatSort, {static: false})
   set sort(sort: MatSort) {
      this.sortiments.sort = sort;
      this.selectedSortiments.sort = sort;
   }

我从这里找到了答案: https://stackoverflow.com/a/47519683/3437868 https://github.com/angular/components/issues/15008#issuecomment-516386055