【发布时间】:2021-03-31 09:30:24
【问题描述】:
ngFor 在我的代码中不起作用。我有以下代码结构。
- AppModule - 包含带有路由器插座的 App 组件
- HomeModule - 包含 Home 组件 - 使用 ngFor。 (ngFor 在这里工作没有问题)
- TestModule - 包含测试模块 - 使用 ngFor(ngFor 在这里不起作用)
我已经在 AppModule 中导入了“BrowserModule”。 我还在 HomeModule 和 TestModule
中导入了“CommonModule”我在 HomeModule home.component.html 文件中有此代码(按预期工作)
<mat-card [class]="(selected_test.id === test.id)? 'test-card selected': 'test-card'" *ngFor="let test of tests" (click)="selectCard($event, test)">
<div class="left">
<div class="title">{{test.title}}</div>
<div class="description">{{test.description}}</div>
</div>
<div class="right">
<div class="question-count">{{test.questions.length}} Question{{(test.questions.length > 1?'s':'')}}</div>
</div>
</mat-card>
我在 TestModule 中有这段代码 test.component.html:
<div *ngFor="let q of test.questions" class="question-item">
<div class="question-title">{{q.prompt}}</div>
<div class="question-options">
<!-- <div *ngFor="let option of question.options" class="question-option">{{option}}</div> -->
</div>
</div>
sn-p 1 中的代码有效,而 sn-p 2 中的代码无效。我不确定这是怎么回事。
编辑:
app.module.ts
import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { AppRoutingModule } from './app-routing.module';
import { AppComponent } from './app.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { MatToolbarModule } from '@angular/material/toolbar'
import { MatCardModule } from '@angular/material/card';
import { HomeModule } from './pages/home/home.module';
import { CommonModule } from '@angular/common';
@NgModule({
declarations: [
AppComponent
],
imports: [
BrowserModule,
AppRoutingModule,
BrowserAnimationsModule,
MatToolbarModule,
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
home.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { HomeComponent } from './home.component';
import { MatButtonModule } from '@angular/material/button'
import { MatCardModule} from '@angular/material/card'
@NgModule({
declarations: [HomeComponent],
imports: [
CommonModule,
MatButtonModule,
MatCardModule
],
exports:[
]
})
export class HomeModule { }
test.module.ts
import { NgModule } from '@angular/core';
import { CommonModule } from '@angular/common';
import { TestComponent } from './test.component';
import { BrowserModule } from '@angular/platform-browser';
@NgModule({
declarations: [TestComponent],
imports: [
CommonModule,
],
exports: [
TestComponent
]
})
export class TestModule { }
【问题讨论】:
-
几个问题:
ng serve日志顶部是否还有其他错误,这些模块是延迟加载还是使用共享模块? -
第一次使用
tests,第二次使用test- 您确定在TestModule中提供单个测试对象吗? -
能否确认
test.questions是否持有数组? -
@NathanBeck - 终端和浏览器中都没有其他错误。这些模块只是使用路由器插座加载。目前没有延迟加载
-
@RandyCasburn - HomeModule 正在渲染多个测试的标题,这就是为什么是复数。在 TestModule 中,我只通过了一个测试。
标签: angular ngfor ng-modules