【发布时间】:2021-02-13 21:17:32
【问题描述】:
我正在尝试使用 *ngFor 呈现 Angular 11 中的帖子列表,但由于某种原因,没有显示任何内容,但是当我删除 *ngFor 并手动显示一些数据而不循环遍历列表时它可以工作。
在控制台上,我发现了这个错误(mat-form-field must contain a MatFormFieldControl)
这是我在 post-list.component.html 上使用的代码:
<mat-accordion multi="true" *ngFor="let post of posts">
<mat-expansion-panel>
<mat-expansion-panel-header> {{ post.title }}</mat-expansion-panel-header>
</mat-expansion-panel>
</mat-accordion>
post-list.component.ts
import { Component } from '@angular/core';
@Component({
selector: 'app-post-list',
templateUrl: './post-list.component.html',
styleUrls:['./post-list.component.css']
})
export class PostListComponent {
posts = [
{title:'First Post',content : 'This is the First post'},
{title:'Second Post',content : 'This is the Second post'},
{title:'Third Post',content : 'This is the Third post'}
];
}
app.module.ts
import { NgModule } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import {FormsModule} from '@angular/forms';
import { AppRoutingModule } from './app-routing.module';
import {MatInputModule } from '@angular/material/input';
import {MatCardModule} from '@angular/material/card';
import {MatButtonModule} from '@angular/material/button';
import {MatToolbarModule} from '@angular/material/toolbar';
import {MatIconModule} from '@angular/material/icon'
import {MatExpansionModule} from '@angular/material/expansion'
import { AppComponent } from './app.component';
import {PostCreateComponent} from './posts/post-create/post-create.component';
import { BrowserAnimationsModule } from '@angular/platform-browser/animations';
import { HeaderComponent } from './header/header.component';
import {PostListComponent} from './posts/post-list/post-list.component'
@NgModule({
declarations: [
AppComponent,
PostCreateComponent,
HeaderComponent,
PostListComponent,
],
imports: [
BrowserModule,
AppRoutingModule,
FormsModule,
BrowserAnimationsModule,
MatInputModule,
MatButtonModule,
MatCardModule,
MatToolbarModule,
MatIconModule,
MatExpansionModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }
post-create.component.html
<mat-card>
<mat-form-field [(ngModel)]="enteredTitle">
<input matInput type="text" />
</mat-form-field>
<mat-form-field>
<textarea rows="6" [(ngModel)]="enteredContent"></textarea>
</mat-form-field>
<button mat-raised-button color="primary" (click)="onAddPost()">
Save Post
</button>
</mat-card>
【问题讨论】:
标签: angular