获取回复的评论信息
有人会说获取回复的评论信息,这不简单么?加个 click 事件不就行了。还记得上一篇文章咱们是如何实现梯形展示评论的么?咱们是通过递归来实现的,怎么添加 click 事件让一个不知道嵌了多少层的组件能够把评论信息传给父组件?首先不具体想怎么实现,我们这个思路是不是对的:把子组件的信息传给父组件?答案是肯定的,我们就是要把不管嵌了多少层的子组件的信息传给 comment.component.ts 这个评论模块的主组件。
Angular 提供了 @Output 来实现子组件向父组件传递信息,我们在 comment-view.component.ts 模块中添加 @Output 向每个调用它的父组件传信息,我们是嵌套的,这样一层一层传出来,直到传给 comment-component.ts 组件。我们看代码怎么实现。
实现代码
comment-view.component.ts
@Component({ selector: 'comment-view', templateUrl: './comment-view.component.html', styleUrls: ['./comment-view.component.css'] }) export class CommentViewComponent implements OnInit { @Input() public comments: Comment[]; // 点击回复时返回数据 @Output() public contentEvent: EventEmitter<Comment> = new EventEmitter<Comment>(); // 用于跳转到回复输入框的url拼接 public url: string = ""; constructor(private router: Router, private activateRoute: ActivatedRoute ) { } ngOnInit(): void { this.url = this.router.url; this.url = this.url.split("#")[0]; this.url = this.url + "#comment"; } reply(comment: Comment) { this.contentEvent.emit(comment); } transferToParent(event) { this.contentEvent.emit(event); } }
comment-view.component.html
<div *ngFor="let comment of comments"> <div class="media"> <div class="pull-left"> <span class="media-object"></span> </div> <div class="media-body"> <h4 class="media-heading">{{ comment.username }} <small class="pull-right">{{ comment.time }} | <a href="{{url}}" rel="external nofollow" rel="external nofollow" (click)="reply(comment)" >{{ 'comment.reply' | translate }}</a></small> </h4> {{ comment.content }} <hr> <comment-view *ngIf="comment.cComments != null" [comments]="comment.cComments" (contentEvent)="transferToParent($event)"></comment-view> </div> </div> </div>
comment.component.ts
@Component({ selector: 'comment', templateUrl: './comment.component.html', styleUrls: ['./comment.component.css'] }) export class CommentComponent implements OnInit { @Input() public comments: Comment[]; // 要回复的评论 public replyComment: Comment = new Comment(); public id: number = 0; public content: string = ""; ngOnInit(): void { } getReplyComment(event) { this.replyComment = event; this.id = this.replyComment.id; this.content = "[reply]" + this.replyComment.username + "[reply]\n"; } }
内容版权声明:除非注明,否则皆为本站原创文章。