Angular4从脏支票中排除属性

Boh*_*s27 2 angular2-forms angular angular4-forms

我已经通过模板驱动的表单实现了一个自定义表单控件,该表单控件将输入包装为html并添加了标签等。它与ngModel上的2way数据绑定可以很好地与表单进行对话。问题是,表单在初始化时会自动标记为脏的。有没有一种方法可以防止这种情况发生,因此我可以在表单上使用这些属性,它们将是准确的?

自定义选择器(除了自动标记为脏以外,此方法还可以正常工作):

<form class="custom-wrapper" #searchForm="ngForm">
            {{searchForm.dirty}}
            {{test}}
            <custom-input name="testing" id="test" label="Hello" [(ngModel)]="test"></custom-input>
            <pre>{{ searchForm.value | json }}</pre>
</form>
Run Code Online (Sandbox Code Playgroud)

自定义输入模板:

<div class="custom-wrapper col-xs-12">
    <div class="row input-row">
        <div class="col-xs-3 col-md-4 no-padding" *ngIf="!NoLabel">
            <label [innerText]="label" class="inputLabel"></label>
        </div>
        <div class="col-xs-9 col-md-8 no-padding">
            <input pInput name="cust-input" [(ngModel)]="value"  />
        </div>
    </div>
</div>
Run Code Online (Sandbox Code Playgroud)

自定义输入组件:

import { ControlValueAccessor, NG_VALUE_ACCESSOR } from "@angular/forms";
import { Component, Input, forwardRef } from "@angular/core";

@Component({
    selector: "custom-input",
    template: require("./custom-input.component.html"),
    providers: [
        {
            provide: NG_VALUE_ACCESSOR,
            useExisting: forwardRef(() => QdxInputComponent),
            multi: true
        }
    ]
})

export class CustomInputComponent implements ControlValueAccessor {
    @Input("value") _value  = "";
    get value() {
        return this._value;
    }
    set value(val: string) {
        this._value = val;
        this.propagateChange(val);
    }
    @Input() noLabel: boolean = false;
    @Input() label: string = "Label required";
    
    propagateChange = (_: any) => {};

    writeValue(value) {
        if (value !== undefined) {
            this.value = value;
        }
    }
    registerOnChange(fn) {
        this.propagateChange = fn;
    }
    registerOnTouched(fn) {}

}
Run Code Online (Sandbox Code Playgroud)

小智 5

我只是用一个属性指令解决了这个问题:

import { Directive } from '@angular/core';
import { NgControl } from '@angular/forms';

@Directive({
    selector: '[ignoreDirty]'
})

export class IgnoreDirtyDirective {
    constructor(private control: NgControl) {
        this.control.valueChanges.subscribe(v => {
            if (this.control.dirty) {
                this.control.control.markAsPristine();
            }
        });
    }
}
Run Code Online (Sandbox Code Playgroud)

您可以按以下方式在代码中使用它:

<input ignoreDirty type="text" name="my-name" [(ngModel)]="myData">
Run Code Online (Sandbox Code Playgroud)