Angular 8 @ViewChild模板变量错误-无法读取未定义的属性'nativeElement'

时间:2019-12-24 14:42:30

标签: angular

我似乎无法让@ViewChild与Angular 8中的模板变量一起使用,它总是返回为undefined

请在下面查看我的示例。一旦计划解决ViewChild问题,我打算在此处添加mdbModal的代码,我只是以输入为例。

console.log(this.hi.nativeElement);行会导致错误:

  

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

view.component.html

<button *ngIf="caseDetail.statusId != 1" type="button" mdbBtn (click)="showClaimStatusModal()">Claim Status</button>
<app-claim-status-modal></app-claim-status-modal>

app.module.ts     从“ ./views/claim-status-modal/claim-status-modal.component”中导入{ClaimStatusModalComponent};

@NgModule({
  declarations: [
    ClaimStatusModalComponent
  ],
  providers: [
    { provide: ClaimStatusModalComponent, useValue: new     ClaimStatusModalComponent() }
  ],
  bootstrap: [AppComponent]
})
export class AppModule { }

view.component.ts

import { Component, OnInit } from '@angular/core';
import { ClaimStatusModalComponent } from '@app/views/claim-status-modal/claim-status-modal.component';

@Component({
  selector: 'app-view',
  templateUrl: './view.component.html'
})
export class ViewComponent implements OnInit {  
  constructor(private claimStatusModalComponent: ClaimStatusModalComponent) { }
  ngOnInit() {
      //Subscribes to observable to get caseDetail
  }

  showClaimStatusModal() {
    this.claimStatusModalComponent.show();
  }
}

claim-status-modal.component.html

<input id="hi" #hi type="text" value="Hi" />

claim-status-modal.component.ts

import { Component, OnInit, ViewChild, AfterViewInit, ElementRef } from '@angular/core';

@Component({
  selector: 'app-claim-status-modal',
  templateUrl: './claim-status-modal.component.html'    
})
export class ClaimStatusModalComponent implements OnInit, AfterViewInit {
  @ViewChild('hi', {static: false}) hi:  any;


  constructor() { }

  ngOnInit() {
  }

  ngAfterViewInit() {
  }

  show() {
    console.log(this.hi);
    console.log(this.hi.nativeElement);    
  }
}

1 个答案:

答案 0 :(得分:0)

您似乎需要为组件#hi设置名称:

<app-claim-status-modal #hi></app-claim-status-modal>