无法读取未定义的属性“ nativeElement”

时间:2020-11-07 07:18:51

标签: angular

为什么使用此代码会出现“无法读取未定义的属性'nativeElement'”的错误:

html

 <div class="modal-body" *ngIf="!filter">
        <div class="text-center">
          <i class="ni ni-building ni-3x"></i>
        </div>
        <div class="table-responsive" #unfilteredData>

        </div>
      </div>

ts

@ViewChild('unfilteredData', {static: true}) unfilteredData: ElementRef;
 constructor(
        private ss: StationsService,
        private modalService: NgbModal,
        private as: AppointmentService,
        private renderer: Renderer2,
    ) {
        this.stations = this.ss.stations;
     }

ngOnInit() {
        this.getLocations();
    }

ngAfterViewInit(): void {
    this.onToggleChange();
}

onToggleChange() {
        if (this.filter) {
            this.showListMessage = 'Filtered';
        } else {
            this.showListMessage = 'Unfiltered';
            this.setupUnfiltered();
        }
    }

setupUnfiltered() {
       
            this.renderer.setProperty(this.unfilteredData.nativeElement, 'innerHtml', <label>XXX</label>);
}

1 个答案:

答案 0 :(得分:2)

摘自官方文档:https://angular.io/api/core/ViewChild#description

视图查询是在调用ngAfterViewInit回调之前设置的。

这意味着viewChild属性仅在ngAfterViewInit(及之后)可用

(您正在尝试在OnInit事件中访问它)

此外,您需要将static更改为false(因为您有一个结构化指令[ngIf]作为viewChild引用的父项)

Stackblitz working example