首页 > 解决方案 > 错误 TS2339:“PostsComponent”类型上不存在属性“addForm”

问题描述

这是错误信息:

ERROR in src/app/components/posts/posts.component.html:6:58 - error TS2339: Property 'addForm' does not exist on type 'PostsComponent'.
<form #postForm="ngForm" (ngSubmit)="addForm(postForm)"> 

src/app/components/posts/posts.component.ts:7:16
templateUrl: './posts.component.html',
Error occurs in the template of component PostsComponent.

在此处输入图像描述

值得注意的是,该错误仅在我在posts.component.html文件中写入以下行时发生:

<form #postForm="ngForm" (ngSubmit)="addForm(postForm)">

这就是我在post/component.ts中的内容:

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

import { PostService } from '../../services/post.service';

@Component({
  selector: 'app-posts',
  templateUrl: './posts.component.html',
  styleUrls: ['./posts.component.css'],  
  providers: [PostService],
}) 
export class PostsComponent implements OnInit {

  constructor(private postService: PostService) { }

  ngOnInit(): void {
  }

}

但我想错误实际上是在post.service.ts中,出现以下行:

import { PostsComponent} from '../components/posts/posts.component'

在介绍性视频中,我正在学习 ( https://www.youtube.com/watch?v=ccBtSAMFjto ),时间是 29:45,上面的行以无法解释的方式出现在第 4 行。事实上,最后一次显示屏幕区域是在 24 分钟,并且该行不存在。

当我在我的代码中编写此行时,它看起来像缺少关系一样带有阴影,而在视频代码中也不会发生同样的情况。我想这与我的错误有关,因为它与“PostsComponent”有关。

在视频的第 17 分钟中,他遇到了同样的问题,并且似乎通过在 ** app.module.ts ** 中添加以下行来解决它:

import { FormsModule } from '@angular/forms';

我发现以前问过类似的问题,但无法弄清楚发现我的错误的常见原因是什么。

标签: angularmean

解决方案


在组件中创建 addForm方法解决您的问题

import { Component, OnInit } from '@angular/core';
import { PostService } from '../../services/post.service';

@Component({
  selector: 'app-posts',
  templateUrl: './posts.component.html',
  styleUrls: ['./posts.component.css'],  
  providers: [PostService],
}) 
export class PostsComponent implements OnInit {

  constructor(private postService: PostService) { }

  ngOnInit(): void {
  }

  addForm(values){
  }

}

推荐阅读