【问题标题】:Cannot read property 'nativeElement' of undefined无法读取未定义的属性“nativeElement”
【发布时间】:2020-11-07 07:18:51
【问题描述】:

为什么我会收到'Cannot read property 'nativeElement' of undefined'的错误:

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>);
}

【问题讨论】:

    标签: angular


    【解决方案1】:

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

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

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

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

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

    Stackblitz working example

    【讨论】:

    • 我认为,由于父 div 上有 ngIf,因此需要将静态属性更改为 false
    • 请检查我在回答的编辑中提供的示例
    • 嗨,我尝试了您提供的相同解决方案,已将@viewChild 设置为静态:false,因为在 html 中父 div 具有 *ngIf 条件此外,函数调用已保留在 ngAfterViewInit 中。错误仍然存​​在任何解决方案都会有所帮助
    猜你喜欢
    • 2018-02-26
    • 2017-12-15
    • 2017-09-28
    • 1970-01-01
    • 2019-03-17
    • 2018-03-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多