[英]Angular 4 keyup.enter not working properly
我在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)
}
}
1.檢查不起作用:
實際上,問題在於您沒有檢查空的新行 。 如果按Enter鍵,則會在文本區域中生成新行,並且該新行將不符合您的條件。
if(typeof this.comment == "undefined" || this.comment === '' || this.comment == null){ }
在您的if條件中,不檢查是否有空的新行。 這就是為什么要處理其他情況的原因。
試試這個
if(typeof this.comment == "undefined" || this.comment === '' || this.comment == null || this.comment == '\n'){ }
第一次輸入按鍵,您可以看到參考。 但我強烈建議您不要使用上述條件。 那只是為了您的理解。
2.console.log根本不打印任何內容
對於新行,我們在控制台或警報消息中看不到任何內容。
使用它會照顧到所有情況
if( this.comment ) {
}
如果該值不是,則將評估為true:
空值
未定義
為NaN
空字符串(“”)
0
假
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.