如何引用ng-template中的元素?

时间:2018-06-24 10:38:36

标签: angular

我正在使用viewChild来引用该元素,但是这使我抛出未定义的错误本机元素。我也尝试设置超时,但仍然收到相同的错误。

    <ng-template #publishAnywherePDF let-c="close" let-d="dismiss">
      <div class="modal-header" *ngIf="!publishError && publishAnywhereStep != 2">
        <h4 class="modal-title" [hidden]="publishAnywhereStep !== 1" tabindex="0" #title>Download Publish Anywhere PDF</h4>
        <h4 class="modal-title" *ngIf="publishAnywhereStep == 3" tabindex="0">Publish Anywhere PDF</h4>
        <button type="button" class="close" aria-label="Close" (click)="d()" role="button">
          <i class="il-clear"></i>
        </button>
 <button type="button" role="button" class="btn btn-small btn-tertiary pull-right" (focus)="focus()">Cancel</button>
    <ng-template>

我正在尝试在h4中访问#title

@Component({
  selector: 'app-publish-anywhere-pdf',
  templateUrl: './publish-anywhere-pdf.component.html',
  styleUrls: ['./publish-anywhere-pdf.component.scss']
})
export class PublishAnywherePdfComponent implements OnInit, AfterViewInit {
   @ViewChild('title') titleRef: ElementRef;
    focus() {
    console.log(this.titleRef.nativeElement);
    }
}

1 个答案:

答案 0 :(得分:1)

运行代码时,不会创建ng-template并将其显示在DOM中,可以使用ngFor,ngIf,ngSwitch等结构性指令来显示它...否则,它会被DOM上的注释所取代,这就是未定义的原因就您而言