Angular 12使用ngx-datatable时ViewChild与TemplateRef赋值报错如何解决
问题解决方案
根因说明
- Angular 12+默认启用
严格类属性初始化检查,未直接赋值的类属性会触发未初始化报错 - 你的
columns数组未声明类型,TypeScript无法识别其内部的cellTemplate、headerTemplate属性允许接收TemplateRef类型值,触发类型不匹配报错 - 你给模板属性加
?可选符后,属性类型变为TemplateRef<any> | undefined,赋值给列配置时类型不兼容问题会更明显
修复步骤
- 给
ViewChild声明的模板属性添加!非空断言操作符:因为你设置了{ static: true },视图初始化完成前(ngOnInit阶段)就一定会完成模板引用的赋值,不存在空值风险,!可以告诉TypeScript该属性一定会被赋值,跳过初始化检查 - 从
@swimlane/ngx-datatable导入Column类型,给columns数组声明为Column[]类型 - 删掉重复导入的
RestService语句,避免编译告警
修复后完整代码
import { Component, OnInit, TemplateRef, ViewChild } from '@angular/core'; import { ColumnMode, Column } from '@swimlane/ngx-datatable'; import { RestService } from '../services/rest.service'; @Component({ selector: 'app-list-views', templateUrl: './list-views.component.html', styleUrls: ['./list-views.component.css'], }) export class ListViewsComponent implements OnInit { // 加!非空断言解决未初始化报错 @ViewChild('editTmpl', { static: true }) editTmpl!: TemplateRef<any>; @ViewChild('hdrTpl', { static: true }) hdrTpl!: TemplateRef<any>; rows = []; // 声明columns的类型为Column数组,解决类型不匹配问题 columns: Column[] = []; ColumnMode = ColumnMode; constructor(private service: RestService) {} ngOnInit() { this.columns = [ { cellTemplate: this.editTmpl, headerTemplate: this.hdrTpl, name: 'Title', }, { cellTemplate: this.editTmpl, headerTemplate: this.hdrTpl, name: 'Views', }, { cellTemplate: this.editTmpl, headerTemplate: this.hdrTpl, name: 'Image', }, ]; } fetch() { this.service.get('myUrl').subscribe((res: any) => (this.rows = res)); } }
额外说明
如果你的模板引用是放在条件渲染块(比如带*ngIf的容器)内的,需要把static改为false,同时把columns赋值逻辑移到ngAfterViewInit生命周期中,避免模板引用未加载完成导致空值问题。
内容的提问来源于stack exchange,提问作者Roman Badillo G
相关产品推荐
相关产品推荐

