Angular 无法读取属性';nativeElement';未定义的

Angular 无法读取属性';nativeElement';未定义的,angular,Angular,为什么在代码中出现“无法读取未定义的属性”nativeElement“的错误: html <div class="modal-body" *ngIf="!filter"> <div class="text-center"> <i class="ni ni-building ni-3x"></i> </div&g

为什么在代码中出现“无法读取未定义的属性”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>);
}
@ViewChild('unfilteredData',{static:true})unfilteredData:ElementRef;
建造师(
私人党卫军:车站服务,
专用modalService:NgbModal,
私人助理:任命服务,
私有渲染器:渲染器2,
) {
this.stations=this.ss.stations;
}
恩戈尼尼特(){
这个.getLocations();
}
ngAfterViewInit():void{
this.onToggleChange();
}
onToggleChange(){
if(this.filter){
this.showListMessage='Filtered';
}否则{
this.showListMessage='Unfiltered';
此设置为未过滤();
}
}
设置未过滤(){
this.renderer.setProperty(this.unfilteredData.nativeElement,'innerHtml',XXX);
}
来自官方文件:

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

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

(您当前正试图在OnInit事件中访问它)

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

来自官方文件:

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

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

(您当前正试图在OnInit事件中访问它)

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


我认为,由于父div上有ngIf,因此需要将static属性更改为false。请检查我在“编辑我的答案”中提供的示例。我尝试了与您提供的相同的解决方案,已将@viewChild设置为static:false,因为在html中父div具有*ngIf条件,并且函数调用已保留在ngAfterViewInit中。但是错误仍然存在,任何解决方案都会有帮助。我认为,由于父div上有ngIf,您需要将static属性更改为false。请检查我在编辑我的回答时提供的示例。我尝试了与您提供的相同的解决方案,已将@viewChild设置为static:false,因为在html中父div具有*ngIf条件,并且函数调用已保留在ngAfterViewInit中。但错误依然存在,任何解决方案都会有所帮助