简体   繁体   English

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

[英]How can I take reference to an element inside ng-template?

I am using viewChild to take reference of that element but it is throwing me error native Element of undefined. 我正在使用viewChild来引用该元素,但它抛出了我未定义的错误本机元素。 I tried set time out also but still getting same error. 我也尝试设置超时,但仍然收到相同的错误。

    <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>

I am trying to access #title in h4 我正在尝试在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);
    }
}

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM