首页 > 解决方案 > Angular:未定义标识符“标题”。'never' 不包含这样的成员。异常问题

问题描述

我正在学习一个教程,但我被卡住了。不知道为什么我会出错。Visual Studio 代码上的错误是“未定义标识符'title'。'never' 不包含这样的成员”对于 post.title 和 post.content

<mat-accordion multi=True *ngIf="posts.length > 0">
  <mat-expansion-panel *ngFor="let post of posts">
    <mat-expansion-panel-header>
      {{ post.title }}
    </mat-expansion-panel-header>
    <p>
      {{ post.content }}
    </p>
  </mat-expansion-panel>
</mat-accordion>
<p class="info-text mat-body-1" *ngIf=" posts.length <= 0" > no posts added yet</p>

在 app.component.ts 中我收到一个错误:“参数‘post’隐式具有‘any’类型”和“‘any’类型的参数不可分配给‘never’类型的参数”

此特定错误位于 onPostadded

import { Component } from '@angular/core';

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'ang-project';

  storedPost = [] ;

  onPostAdded(post) {
    this.storedPost.push(post);
  }
}

让我知道是否需要显示更多不同文件的代码。我会很感激我能得到的任何帮助。

编辑:对于函数“*ngFor="let post of posts”,由于某种原因,帖子是类型 never : (property) PostListComponent.posts: never[]

我不知道为什么会这样。

我应该补充说,posts 变量是一个 const 数组。

import {Component, EventEmitter} from '@angular/core'

@Component({
  selector: 'app-post-create',
  templateUrl: './post-create.component.html',
  styleUrls: ['./post-create.component.css']
})
export class PostCreateComponent {
  enteredContent = '';
  enteredTitle = '';
  postCreated = new EventEmitter();

  onAddPost() {
    const posts = {
      title: this.enteredTitle,
      content: this.enteredContent
    };
    this.postCreated.emit(posts);
  }
}

这是 post-list-component.ts

import { Component, Input } 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'}
  // ];

  @Input() posts: IPost[] = [];

我收到一个错误:“找不到名称‘IPost’”

标签: angulartypescriptangular-material

解决方案


我不知道这是否:

<mat-accordion multi=True *ngIf="posts.length > 0">
  <mat-expansion-panel *ngFor="let post of posts">
    <mat-expansion-panel-header>
      {{ post.title }}
    </mat-expansion-panel-header>
    <p>
      {{ post.content }}
    </p>
  </mat-expansion-panel>
</mat-accordion>
<p class="info-text mat-body-1" *ngIf=" posts.length <= 0" > no posts added yet</p>

是 的模板AppComponent。但如果是,那么不要检查*ngIf="posts.length > 0"应该是*ngIf="storedPost.length > 0"*ngIf="posts.length <= 0"应该是*ngIf="storedPost.length <= 0"*ngFor="let post of posts"应该是*ngFor="let post of storedPost"。因为您在提交时将您的帖子添加到 storedPost


推荐阅读