简体   繁体   English

Angular2反应形式,原始状态下的FormControl默认值

[英]Angular2 Reactive forms, FormControl default value in pristine status

I have created a form which allows the user to add additional text-inputs by clicking a button. 我创建了一个表单,该表单允许用户通过单击按钮来添加其他文本输入。 The FormControl s behind these inputs are stored in a FormArray inside of a FormGroup . 这些输入后面的FormControl存储在FormArray内部的FormGroup

I want to provide a default value for these inputs, that is going to be submitted if they are pristine. 我想为这些输入提供一个默认值,如果它们是原始的,它将被提交。 If the user changes the value of the input, which changes it to dirty, I do not want the default value to be submitted or displayed. 如果用户更改了输入的值(将其更改为脏),则我不希望提交或显示默认值。

I currently am displaying the inputs like this, as the placeholder attribute does exactly what I want, displaying the default name, only if the input has not been changed. 我目前正在显示这样的输入,因为占位符属性完全符合我的要求,仅当输入未更改时才显示默认名称。

<div
    formArrayName="names" 
    *ngFor="let server of names.controls; let i = index; trackBy:trackByFn">
        <span>{{ i + 1 }}</span>
        <input 
        type="text" 
        formControlName="{{i}}"
        placeholder="{{defaultName}}">

</div>

To validate the names I have created the following validation function: 为了验证名称,我创建了以下验证功能:

export function validateServerName(form: FormGroup): ValidationErrors | null {
    const names: string[] = form.value[CREATE_FORM_KEY_NAMES];

    for (const name of names) {
        if (name.trim() === '') {
            return {
                invalidName: true
            };
        }
    }

    return null;
}

Here I am having trouble figuring out if the element is dirty or pristine, as form.value[key] only returns a string array, not an array of the FormControls. 在这里,我很难弄清楚该元素是脏的还是原始的,因为form.value[key]仅返回一个字符串数组,而不是FormControls的数组。

I am looking for either an easier way to do what I am trying to achieve, or a way to validate the form properly. 我正在寻找一种更简单的方法来完成我要达到的目标,或者寻找一种正确验证表单的方法。

you can check the control status using 您可以使用以下命令检查控制状态

if touched is true then its dirty 如果感动是真的,那么它是肮脏的

this.form.get('controlname').touched 

and for pristine you can check like 对于原始的,你可以检查像

this.form.get('controlname').pristine

UPDATE 更新

for form array it will be something like 对于表单数组,它将类似于

  let val = this.user.get('<FormArray>') as FormArray;
  console.log(val.at(index));

you can now use pristine and touched on this variable 您现在可以使用pristinetouched此变量

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM