首页 > 解决方案 > 我无法使用 Angular 中的输出和 EventEmitter 在应用程序组件中获取组件(帖子)的属性

问题描述

它说任何类型的参数是不可分配的。
我应该在 app.component 中导入其他内容吗?
你能告诉我我做错了什么吗?app.component.ts

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

@Component({
  selector: 'app-root',
  templateUrl: './app.component.html',
  styleUrls: ['./app.component.css']
})
export class AppComponent {
  title = 'test';
  posts=[];
  onAddedPost(post){
    this.posts.push(post)
  }
}

这就是问题所在。onAddedPost 中的帖子是问题所在。创建后.component.ts

import { sharedStylesheetJitUrl } from '@angular/compiler';
import { Component, EventEmitter, Injectable, Output, OutputDecorator } from '@angular/core';
@Component({
  selector: 'app-post-create',
  templateUrl: './post-create.component.html',
  styleUrls: ['./post-create.component.css']
})
export class PostCreateComponent {
  enteredContent='';
  enteredTitle='';
  @Output() postCreated = new EventEmitter();
  onAddPost(){
    const post={title:this.enteredTitle,content:this.enteredContent};
    this.postCreated.emit(post);
  }

}

app.component.html

<app-header></app-header>
<main>
<app-post-create (postCreated)="onPostAdded($event)" ></app-post-create>
<app-post-list [posts]="storedPosts"></app-post-list>
</main>

app.module.ts

@NgModule({
  declarations: [
    AppComponent,
    PostCreateComponent,
      HeaderComponent,
      PostListComponent
   ],
  imports: [
    BrowserModule,
    AppRoutingModule,
    FormsModule,
    BrowserAnimationsModule,
    MatInputModule,
    MatCardModule,
    MatButtonModule,
    MatToolbarModule,
    MatExpansionModule,

  ],

  bootstrap: [AppComponent]
})
export class AppModule { }

标签: angularangular-directive

解决方案


很可能这是一个 TSLint 错误,因为它无法推断类型。注意:这不会影响应用程序,因为编译后的 JS 无法识别 TS 类型。

但是要解决它,您可以定义该类型的 Typescript 接口。

  1. 定义模型

post.ts

export interface Post {
  title?: string;
  content?: string;
}
  1. 使用此模型在两个组件中定义类型。

创建后.component.ts

import { sharedStylesheetJitUrl } from '@angular/compiler';
import { Component, EventEmitter, Injectable, Output, OutputDecorator } from '@angular/core';

import { Post } from './post';

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

  @Output() postCreated: EventEmitter<Post> = new EventEmitter<Post>();

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

app.component.ts

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

import { Post } from './post';

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

  onAddedPost(post: Post) {
    this.posts.push(post);
  }
}

推荐阅读