【问题标题】:Argument of type '"content"' is not assignable to parameter of type 'TemplateRef<any>'.ts(2345)'"content"' 类型的参数不可分配给 'TemplateRef<any>'.ts(2345) 类型的参数
【发布时间】:2021-09-18 04:14:01
【问题描述】:

我想在单击按钮时打开一个模式。但我无法将模板引用传递给我的模态。我在 nav.component.ts 中遇到类型错误

在我的 nav.component.html

<button *ngIf="!loggedIn" class="btn btn-outline-success ms-3" (click)="open()">
    Sign Up
</button>

在 nav.component.ts 中:已编辑

@Component({
  selector: 'app-nav',
  templateUrl: './nav.component.html',
  styleUrls: ['./nav.component.scss']
})
export class NavComponent implements OnInit {

  constructor(
    public modalShared : ModalComponent
  ) { }

  ngOnInit(): void { 
  }

  open() {
    this.modalShared.openModal("'content'");
  }

}

在我的 modal.component.ts

import { Component, OnInit, TemplateRef, Input, Injectable } from '@angular/core';
import { BsModalService, BsModalRef } from 'ngx-bootstrap/modal';

@Injectable({
  providedIn: 'root'
})

@Component({
  selector: 'app-modal',
  templateUrl: './modal.component.html',
  styleUrls: ['./modal.component.scss']
})
export class ModalComponent implements OnInit {

  modalRef: BsModalRef = new BsModalRef();

  constructor(
    private modalService: BsModalService
  ) { }

  ngOnInit(): void {
  }

  openModal(template:TemplateRef<any>){
    this.modalRef = this.modalService.show(template);
  } 

}

还有我的 modal.component.html

<ng-template #content>
    <p>Click button is working!</p>
</ng-template>

【问题讨论】:

  • 你能添加更多nav.component.ts的代码吗,就像你声明this,modalShared的地方一样?
  • @Yogesh,我已经对其进行了编辑并在nav.component.ts中添加了更多代码

标签: html angular typescript


【解决方案1】:

您传递的是字符串而不是预期的 TemplateREf。您需要使用@ViewChild 来获取对templateRef 的引用。

@ViewChild('content')
content: TemplateRef<any>;

...

open() {
  this.modalShared.openModal(this.content);
}

【讨论】:

  • 仍然出现错误。 “'TemplateRef | undefined' 类型的参数不可分配给'TemplateRef' 类型的参数。'undefined' 类型不可分配给'TemplateRef'.ts(2345) 类型”
  • @Viewchild('content') content!: TemplateRef&lt;any&gt;
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2022-06-16
  • 2022-11-30
  • 1970-01-01
  • 1970-01-01
  • 2021-09-06
  • 1970-01-01
相关资源
最近更新 更多