【问题标题】:error TS2339: Property 'addForm' does not exist on type 'PostsComponent'错误 TS2339:“PostsComponent”类型上不存在属性“addForm”
【发布时间】:2020-09-25 15:09:48
【问题描述】:

这是错误信息:

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';

我发现以前有人问过类似的问题,但不知道发现我的错误的常见原因是什么。

【问题讨论】:

  • 您必须定义一个方法才能使用它,addForm 方法是在哪里定义的?在服务中?
  • 在视频中(最少 17:20),它似乎在 app.module.ts “import {FormsModule} from '@ angular / forms';”中定义了它.我在下面尝试了 Edison 的建议,但没有奏效。

标签: angular mean


【解决方案1】:

在组件中创建 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){
  }

}

【讨论】:

  • 我添加了“ addForm(){} ”行并且错误保持不变。
  • 请尝试将addForm() 更改为addForm(values),例如:我已经更新了我的答案
  • 是的,好像有什么东西动了。但现在我收到以下错误消息:“src/app/components/posts/posts.component.html:8:87 - 错误 TS2341:属性 'postService' 是私有的,只能在类 'PostsComponent' 中访问。”
猜你喜欢
  • 2019-01-21
  • 2016-08-13
  • 2017-12-20
  • 2016-11-14
  • 2017-10-24
  • 2021-08-10
  • 2018-11-17
  • 2021-06-22
  • 2020-11-30
相关资源
最近更新 更多