在上一篇博客中,我们开发了评论系统的前端部分,介绍了angular中模板的概念。在这篇博客中,我们将继续开发评论系统的前端部分,并介绍组件间通信的相关内容。
打开comments.component.ts文件,输入以下内容:
//comments.component.ts
import {
Component, Input, OnInit } from '@angular/core';
import {
CommentService } from 'src/app/service/comment.service';
@Component({
selector: 'app-comments',
templateUrl: './comments.component.html',
styleUrls: ['./comments.component.scss']
})
export class CommentsComponent implements OnInit {
showComment:boolean[]
@Input() commentTree:any;
@Input() storyId:number;
constructor() {
this.showComment = [false];
this.storyId = 0;
}
ngOnInit(): void {
}
showCommentForm(storyId:number){
this.showComment[storyId] = !this.showComment[storyId];
}
}
这个组件中有两个属性:commentTree和storyId,前者用于存放评论树内容,而后者表示当前评论树属于哪个故事。
由于我们这个控件要作为storyList的子控件使用,即需要由storyList指定comments组件要放在哪个故事下面,因此我们使用@Input()修饰器来修饰commentTree和storyId参数,表明storyList组件可以指定comments组件中这两个属性的值:
底下的showCommentForm函数用来反转showComment数组中对应元素的值,控制评论树中评论表单的隐现。
这样,我们这个comments的前端部分就开发完了,下面让我们实现另一个组件commentForm,
这个组件用于让用户发表评论。
打开commentform/commentform.component.html,输入以下代码:
<!--commentform.component.html-->
<form nz-form [formGroup]="commentForm" (ngSubmit)="publishComment()">
<nz-form-item>
<nz-form-control>
<input formControlName="content" nz-input placeholder="说点什么" />
</nz-form-control>
</nz-form-item>
<nz-form-item>
<nz-form-control>
<button nz-button nzType="primary">发表</button>
</nz-form-control>
</nz-form-item>
</form>
这个组件没什么说的,就是一个简单的表单。
下面打开commentform.component.ts文件,输入以下代码:
//commentform.component.ts
import {
Component, EventEmitter, Input, OnInit, Output } from '@angular/core';
import {
FormControl, FormGroup