当用户尝试发送一个表单,将该字段留空时,我想在数量文本字段上显示MDL错误消息。这个领域就像:
<mdl-textfield
#quantityBox
type="text"
label="Num."
pattern="-?[0-9]*(\.[0-9]+)?"
error-msg="Insert a number!"
[(ngModel)]="selectedBoxQuantity"
floating-label
class="no-wrap"></mdl-textfield>
我可以访问调用ViewChild的字段组件:
@ViewChild('quantityBox') private quantityBox: MdlTextFieldComponent;
但显然我只能更改错误信息:
this.quantityBox.errorMessage = "New error message";
如何在输入字段中输入无效值的情况下强制显示消息?
当我点击/点击+按钮时,我想要实现的与此类似:
我通过向div添加类来解决它。这是我的解决方案:
HTML:
<div id="id_div" class="mdl-textfield mdl-js-textfield mdl-textfield--floating-label">
<input id="id" class="mdl-textfield__input" type="text">
<label class="mdl-textfield__label" for="id">ID</label>
<span id="id_msg" class="mdl-textfield__error"></span>
</div>
JS:
function submit() {
if (document.getElementById("id").value === "") {
document.getElementById("id_div").classList.add("is-invalid");
document.getElementById("id_div").classList.add("is-dirty");
document.getElementById("id_msg").innerText="Invalid ID";
return;
}
//other code...
}
我不太确定你想要达到的目标 - 但这里有一个解决方案,你可以帮忙找到它。将required
属性添加到mdl-textfield
并使error-msg
属性成为一个真实属性,因此angular会对其进行求值:
<mdl-textfield
required
type="text"
label="Num."
pattern="-?[0-9]*(\.[0-9]+)?"
[error-msg]="message"
[(ngModel)]="selectedBoxQuantity"
floating-label
class="no-wrap"></mdl-textfield>
在您的组件中添加以下代码:
public message = 'Insert a number!';
public selectedBoxQuantity_: number;
get selectedBoxQuantity() {
return this.selectedBoxQuantity_;
}
set selectedBoxQuantity(v: string){
this.selectedBoxQuantity_ = v;
this.message = v.length === 0 ? 'Insert a number!' : 'Insert a valid number';
}
此文本字段现在显示消息“插入数字!”在初始加载时,因为该字段是必需的,并且消息设置为“插入数字!”。如果用户键入方法,则调用selectedBoxQuantity
。如果值仍为空,则错误消息仍为插入数字!如果没有,则错误消息设置为“插入有效数字”。如果输入与您的模式不匹配,则会显示新的错误消息。如果输入是数字,则错误消息消失。