You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Angular中ngIf用else模板报错:Property 'noPartite'不存在于MainPageComponent

问题

开发Angular页面展示足球比赛结果,想在无比赛时显示提示信息。用*ngIf判断live数组长度大于0,else中引用ng-template时出现错误:Property 'noPartite' does not exist on type 'MainPageComponent'。

相关HTML代码

<div *ngIf="live.length > 0">
    <h1 style="color: red;">Live ScoreBoard</h1>
    <div *ngFor="let data of live">
        <div class="title-box">
            <p id="elapsed">{{ data.fixture.status.elapsed }}'</p>
        </div>
        <div class="title-box">
            <div class="team">
                <img id="homeLogo" src="{{ data.teams.home.logo }}">
                <p id="homeName">{{ data.teams.home.name }}</p>
            </div>
            <p id="goals">{{ data.goals.home }} - {{data.goals.away}}</p>
            <div class="team">
                <img id="awayLogo" src="{{ data.teams.away.logo }}">
                <p id="homeName">{{ data.teams.away.name }}</p>
            </div>
        </div>
        <hr>
    </div>
    <ng-template #noPartite>
        <p>No matches are scheduled today, however you can check the results of past matches <a routerLink="/matchday">here</a>and the standings here.</p>
    </ng-template>
</div>

终端报错信息

Error: src/app/Components/main-page/main-page.component.html:3:43 - error TS2339: Property 'noPartite' does not exist on type 'MainPageComponent'.

3         <div *ngIf="live.length > 0; else noPartite">
                                            ~~~~~~~~~

  src/app/Components/main-page/main-page.component.ts:7:16
    7   templateUrl: './main-page.component.html',
                     ~~~~~~~~~~~~~~~~~~~~~~~~~~~~
    Error occurs in the template of component MainPageComponent.

解决方案

  • 调整ng-template的位置:你把#noPartite模板放在了*ngIf控制的<div>内部,当live.length > 0不成立时,整个<div>会被DOM移除,模板也跟着消失,Angular找不到这个引用变量。把ng-template移到这个<div>外面即可:
<div *ngIf="live.length > 0; else noPartite">
    <!-- 比赛列表内容 -->
</div>
<ng-template #noPartite>
    <p>No matches are scheduled today, however you can check the results of past matches <a routerLink="/matchday">here</a> and the standings here.</p>
</ng-template>
  • 可选:使用*ngIf的then/else语法(结构更清晰):
<ng-template #matchesTemplate>
    <h1 style="color: red;">Live ScoreBoard</h1>
    <!-- 比赛列表内容 -->
</ng-template>
<ng-template #noPartite>
    <p>No matches are scheduled today...</p>
</ng-template>

<div *ngIf="live.length > 0; then matchesTemplate else noPartite"></div>

内容的提问来源于stack exchange,提问作者Theny29

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 07:05:22