Search code examples
angularngmodel

How to keep values in disabled input control when model changes?


I have a JSON object using which I create a form having one disabled control and one enabled input control for each value, Disabled inputs are for reference for user while he may change values in active Input control. I need to keep values fixed in disabled Input, while using the same model. Any help will be appreciated.enter image description here


Solution

  • If you are using template driven forms, you can use one-time binding on the disabled elements so they won't update.

    This will be even easier with reactive forms as the form model and data model are already separate.

    Here is an example (template driven forms):

    Normally bound (editable) item:

          <input class="form-control"
                 id="productNameId"
                 type="text"
                 placeholder="Name (required)"
                 required
                 minlength="3"
                 [(ngModel)]=product.productName
                 name="productName" />
    

    One-time binding (non-editable) item:

          <input class="form-control"
                 id="productNameId"
                 type="text"
                 placeholder="Name (required)"
                 required
                 minlength="3"
                 ngModel=product.productName   /* <- the difference is here */
                 name="productName" />
    

    Here is a stackblitz: https://stackblitz.com/edit/angular-hnyy5d

    [(ngModel)] -> two-way binding

    [ngModel] -> one-way binding

    ngModel -> one-time binding (only binds the initial value and won't update)