在 angular2 中输入 space 以外的字符时启用按钮
Enable button on entering a character other than space in angular2
我有一个文本区域形式的评论部分,如果用户开始在文本区域中输入一些字符(space 除外),我想启用另一个按钮。我怎样才能在 angular2 中做到这一点?
我已经让它工作了,但我的问题是即使用户在文本区域输入 'space' 按钮也会启用。我怎样才能更正此行为,以便只有当用户写东西时按钮才会启用?
在html中:
<textarea id="comments"
class="comments-text"
[(ngModel)]="text"
(ngModelChange)="onAddComment($event)"
name="text"></textarea>
<button [disabled]="EnableButton()">
在组件中:
public onAddComment(event: string): void {
this.passedString = event;
}
public EnableButton(): void {
return !!this.passedString;
}
buttonIsDisabled:boolean=true;
public onAddComment(event: string): void {
this.buttonIsDisabled=true;
let passedString = event;
if (/\S/.test(passedString)) {
// string is not empty and not just whitespace
// activate button
this.buttonIsDisabled=false;
}
}
<button [disabled]="buttonIsDisabled">
这应该可以解决问题。看
How can I check if string contains characters & whitespace, not just whitespace?
您可以检查每个 textarea
值的变化,如果它包含除空格以外的任何其他符号。
onAddComment() {
if (this.text.replace(/\s/g, '').length == 0) {
this.check = true;
} else {
this.check = false;
}
}
trim() 可以用来去掉空格。
我有一个文本区域形式的评论部分,如果用户开始在文本区域中输入一些字符(space 除外),我想启用另一个按钮。我怎样才能在 angular2 中做到这一点?
我已经让它工作了,但我的问题是即使用户在文本区域输入 'space' 按钮也会启用。我怎样才能更正此行为,以便只有当用户写东西时按钮才会启用?
在html中:
<textarea id="comments"
class="comments-text"
[(ngModel)]="text"
(ngModelChange)="onAddComment($event)"
name="text"></textarea>
<button [disabled]="EnableButton()">
在组件中:
public onAddComment(event: string): void {
this.passedString = event;
}
public EnableButton(): void {
return !!this.passedString;
}
buttonIsDisabled:boolean=true;
public onAddComment(event: string): void {
this.buttonIsDisabled=true;
let passedString = event;
if (/\S/.test(passedString)) {
// string is not empty and not just whitespace
// activate button
this.buttonIsDisabled=false;
}
}
<button [disabled]="buttonIsDisabled">
这应该可以解决问题。看 How can I check if string contains characters & whitespace, not just whitespace?
您可以检查每个 textarea
值的变化,如果它包含除空格以外的任何其他符号。
onAddComment() {
if (this.text.replace(/\s/g, '').length == 0) {
this.check = true;
} else {
this.check = false;
}
}
trim() 可以用来去掉空格。