【发布时间】:2018-04-06 05:49:40
【问题描述】:
我在 keyup.enter 上触发 addComment 函数并单击事件。 我已经在 addComment 函数中应用了 if 条件,如果 ngModel 值注释趋于为空或未定义,那么我会警告一个错误。但是,如果我为 keyup.enter 编写代码,那么我的验证将停止工作。 console.log 根本不打印任何内容,并且检查不起作用。 这发生在 keyup.enter 而不是 click 事件。 请提出一些修复建议。
HTML
<div class="row">
<div style="margin-left: 30px; margin-top: 1%;" class="col-lg-6 col-sm-12">
<textarea style="border-radius: 20px;display:inline!important;" (keyup.enter)="addComment($event)" [(ngModel)]="comment" class="form-control" placeholder="Add Comment">
</textarea>
<button (click)="addComment($event)" style="display:inline-block;margin-top: 2%" class="btn-success">Add Comment</button>
</div>
</div>
组件
import {Component, OnInit, ElementRef, ViewChild, Renderer2} from '@angular/core';
import { CommentsDataService} from "../../services/comments/comments-data.service";
@Component({
selector: 'app-list-comments',
templateUrl: './list-comments.component.html',
styleUrls: ['./list-comments.component.css']
})
export class ListCommentsComponent implements OnInit {
commentsData; // Json array of Comment Data received from service.
comment:string; // Commennt text; declaration.
postId = 1;
getComments; // Declaration of function.
@ViewChild('commentData.id') commentDataId; // id of reply textarea
/**
* Append new comment
* @param comment
*/
addComment(comment)
{
console.log("comment text:"+this.comment);
if(typeof this.comment == "undefined" || this.comment === '' || this.comment == null)
{
alert("Add some text!");
return false;
}
else
{
this.commentsData.push({
root_id:"2",
target_id: "12",
text: this.comment,
comment_posted_by:"Jack",
comment_posted_by_image:'../../assets/images/no-user.png'
})
}
}
addReply();
addReply()
{
var textarea = this.commentDataId.nativeElement;
alert(this.commentDataId);
}
constructor(private commentsDataService:CommentsDataService, private renderer: Renderer2 ) {
}
ngOnInit() {
this.commentsData = this.commentsDataService.getComments(this.postId);
console.log( this.commentsData)
}
}
【问题讨论】: