- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我一直在尝试在 Ionic/Angular2 中使用模型形式。我有一个表格,我想做一些条件验证。用户从 6 个必填字段开始,然后可以在“手动”和“自动”处理之间进行选择。如果选择“自动”,则会呈现 3 个以上的表单输入/选择。我希望这 3 个字段从不需要变为必需。
这是开始的模型:
this.myForm = this.formBuilder.group({
name: ['', Validators.compose([Validators.required, Validators.maxLength(45), Validators.minLength(2)])],
img: [''],
longDescription: ['', Validators.compose([Validators.required, Validators.maxLength(200)])],
shortDescription: ['', Validators.compose([Validators.required, Validators.maxLength(45)])],
processingType: [this.PROCESSING_TYPE.MANUAL],
discountType: ['' ],
discountRule: ['' ],
discountAmount: ['' ], // money, isNumbersOnly handled by custom validator
product: [''],
dateRuleDays: ['' ],
dateRuleTimeStart: ['' ],
dateRuleTimeEnd: ['' ],
startDate: ['', Validators.required],
expiryDate: ['', Validators.required ]
});
discountType、discountRule、discountAmount 是我想切换为必需的 3 个字段。
这是我尝试过的:
调用 setProcessingType fn 的标记(如果需要,我可以提供完整页面)
<!-- automatic or manual -->
<h4 margin-top text-center>Processing Type</h4>
<ion-row text-center>
<ion-col width-50>
<button class="width-80" color="primary" (click)="setProcessingType(PROCESSING_TYPE.MANUAL)" ion-button margin-top>{{ PROCESSING_TYPE.MANUAL }}</button>
</ion-col>
<ion-col width-50>
<button class="width-80" color="primary" (click)="setProcessingType(PROCESSING_TYPE.AUTOMATIC)" ion-button margin-top>{{ PROCESSING_TYPE.AUTOMATIC }}</button>
</ion-col>
</ion-row>
当用户在“手动”和“自动”按钮之间单击时,将调用 setProcessingType。 type: string 是我将设置为 processingType 的新值。
setProcessingType(type: string): void {
this.myForm.patchValue({ // i welcome comments to correct this to 'setValue()' if needed
processingType: type
});
let formCtrls = ['discountType', 'discountRule', 'discountAmount', 'dateRuleDays', 'dateRuleTimeStart', 'dateRuleTimeEnd'];
let add = [Validators.required];
let empty = [];
formCtrls.forEach((key, index) => {
if (this.myForm.controls && this.myForm.controls[key]) {
if (type === this.PROCESSING_TYPE.AUTOMATIC) {
this.myForm.controls[key].setValidators([Validators.required]);
} else {
console.log('resetting validators...');
this.myForm.controls[key].setValidators([]);
console.log('errors on : ', key, this.myForm.controls[key].errors);
// this.myForm.controls[key].markAsUntouched(); // attempt 3928
// this.myForm.controls[key].markAsPristine() // attempt 3929
//this.myForm.controls.updateValueAndValidty(); // this throws an error
}
}
})
console.log('new form controls: ', this.myForm.controls);
我还订阅了“processingType”valueChanges,我在其中运行与上述函数相同的逻辑
this.myForm.get('processingType').valueChanges.subscribe(data => this.onProcessingTypeChanged(data));
以下是我尝试向其中添加验证器的值的日志中的一些屏幕截图:
开始(应该怎样)...
基于以上怀疑,我怀疑
this.myForm.controls.updateValueAndValidty();
或者 this.myForm.controls[key].updateValueAndValidity();
是问题所在,但正如我在代码中评论的那样,这两个问题都引发了“不是函数”错误。
我用谷歌搜索了条件验证、angular2 表单模型、动态添加验证器等的几乎所有组合...链接太多,无法在此处列出,哈哈。
希望这足以让某人帮助诊断问题。
提前致谢。
最佳答案
更新:2017 年 4 月 3 日
感谢对此 post 的评论,这里的正确答案是将控件上的错误显式设置回 null。
例子:
formCtrls.forEach((key, index) => {
if (this.myForm.controls && this.myForm.controls[key]) {
if (data === this.PROCESSING_TYPE.AUTOMATIC)
this.myForm.controls[key].setValidators([Validators.required]);
else {
this.myForm.controls[key].validator = [];
this.myForm.controls[key].setErrors(null); // CORRECT WAY- NOW VALIDATORS ARE GONE AND ERRORS ARE NULL
}
}
})
旧答案
我似乎解决了这个问题,但我对此并不满意。感觉像:
1.) 我错过了执行此操作的明显正确方法。
2.) 这是一个巨大的 hack。
3.) 这是一个错误(我对此非常怀疑 - 我通常认为在这种情况下我错了)。
遍历控件并使用 setValidators() 实际上是有效的,直到我尝试了上面@Sampath 的回答(它的工作方式与 setValidators() 相同,但没有解决问题),我才意识到这一点。
为了解决这个问题,每次触发 valueChanges 观察者的回调时,我都会明确地将每个输入的值设置为一个空字符串。
代码:
onProcessingTypeChanged(data) {
let formCtrls = ['discountType', 'discountRule', 'discountAmount', 'dateRuleDays', 'dateRuleTimeStart', 'dateRuleTimeEnd'];
let add = [Validators.required];
let empty = [];
let newValue;
if (data === this.PROCESSING_TYPE.AUTOMATIC) newValue = "";
else newValue = " "; // SET TO AN EMPTY STRING
this.myForm.patchValue({
discountType: newValue,
discountRule: newValue,
discountAmount: newValue,
product: newValue,
dateRuleDays: newValue,
dateRuleTimeStart: newValue,
dateRuleTimeEnd: newValue,
});
formCtrls.forEach((key, index) => {
if (this.myForm.controls && this.myForm.controls[key]) {
if (data === this.PROCESSING_TYPE.AUTOMATIC)
this.myForm.controls[key].setValidators([Validators.required]);
else
this.myForm.controls[key].setValidators([]);
}
})
经过大量探索后,错误 (myForm.controls[key].errors) 似乎正在针对此返回的闭包在内部进行处理:
function(control) {
return isEmptyInput(control.value) : { 'required': true } ? null;
}
因此,据我所知,通过不将每个值重置为空字符串(我觉得这很奇怪,b/c 空字符串是假的,但在闭包中它作为非空输入传递), angular 将每个输入注册为空,并将错误对象设置为 { required: true },因此将表单注册为仍然无效,即使每个输入都没有必需的验证器。
不会将此标记为正确 - 如果有人更正此逻辑或有类似问题,我们希望对此提供反馈。
关于javascript - 尝试使用 Angular2 表单模型做条件验证器。尝试使用 myForm.setValidators(),但似乎不起作用,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/43152697/
说真的,你怎么能在不发疯的情况下处理所有这些异常呢?我是不是读了太多关于异常处理的文章或什么?我尝试重构了几次,但每次似乎都以更糟糕的结果告终。也许我应该承认确实会发生异常(exception)情况,
背景 两者 try/rescue和 try/catch是 Elixir 中的错误处理技术。根据 corresponding chapter在介绍指南中。 Errors can be rescued u
每当我尝试在 Raspberry PI 上运行此 python 脚本时,我都会遇到问题: import socket import sys # Create a TCP/IP socket sock
我想知道一些关于 PHP 的 try , catch声明。 让我们考虑以下示例。 abstract class ExceptionA extends Exception {} class Except
我的 laravel v5.4 项目中有两个模型,user 和 admin。 在 config/auth.php 中,我向守卫和提供者添加了管理员,如下所示: 'guards' => [ 'w
try: r = requests.get(url, params={'s': thing}) except requests.ConnectionError, e: print e
我有以下代码。 但是,它并不能捕获所有错误,而我仍然会收到“throw er;//未处理的'错误'事件”。 为什么是这样? app.post('/api/properties/zip/:zip/bed
问题与细节 我正在使用自定义错误处理,遇到的错误之一是“路径中的非法字符”。我有一个自定义函数,旨在通过路径字符串查找此类非法字符,并在找到它们时引发自定义错误。但是我发现,取决于非法字符,Test-
This question already has answers here: How do I catch a numpy warning like it's an exception (not j
我正在使用其他人的代码,但我不熟悉try/catch,因此我举了一个类似的小例子。在第11行上,如果我写了error(''),似乎没有发现错误并增加了索引j。但是,编写error(' ')或error
我在我的一个程序中遇到了这个问题,在这种情况下,尝试/异常(exception)的错误使程序变得更好,以防用户意外输入了他们不应该输入的内容。它仍然给我错误,我为为什么感到困惑。如果对我的问题确实很重
我在尝试TRY ... CATCH块时遇到问题。有人可以解释为什么以下代码无法执行我的sp吗? DECLARE @Result int SET @Result = 0 BEGIN TRY SE
我有一个相当大的 powershell 脚本,其中包含许多(20 多个)执行各种操作的函数。 现在所有代码实际上都没有任何错误处理或重试功能。如果某个特定的任务/功能失败,它就会失败并继续。 我想改进
为什么我尝试时需要导入 inputmismatchException catch(InputMismatchException e){ System.out.println("
我对此感到困惑 - 我为辅助方法编写了一个 try/catch 。它的目的是捕获任何无效输入(任何不是“男性”或“女性”的内容(没有特定情况)。如果输入无效,它将通知用户,然后让他们重试。如果有效,则
我有时会发现自己处于如下场景。尽可能简单地陈述问题 “有时我会创建一段代码,Java 让我将其包含在 try/catch 语句中。我没有使用 catch,所以我将其留空。为什么这是错误的?” boo
我有点困惑为什么当我不使用 Try block 时会出现 Try block 错误。 我在代码块底部附近收到错误通知。如果我不使用 try/catch,有人可以向我解释为什么会发生这种情况吗? 它是否
我已经盯着我的电脑两个小时了,我不知道我做错了什么。谁能帮助我看到光明? package blackjack; import java.util.Random; import java.util.Sc
我想将方法保存在 Enum 中,但 Class.getDeclaredMethod 抛出 NoSuchMethodException,那么我该如何处理呢?我的代码: public enum Car
这个问题已经有答案了: Executing multi-line statements in the one-line command-line (18 个回答) 已关闭 3 年前。 如何使用try.
我是一名优秀的程序员,十分优秀!