Angular 5 Set default value on template driven form input

16,657

I've updated your code below. I don't see any component code, so I guessed on the appropriate bindings.

<div class="form-group">
    <label for="imdb">Edit IMDb ID</label>
    <input #editImdb type="text" class="form-control" 
           id="imdb" [(ngModel)]="editMovie.imdb" required />
    <div class="mt-1" style="color:red">
        *required
    </div>
</div>

<div class="form-group">
    <label for="trailer">Edit Youtube Trailer</label>
    <input #editTrailer type="text" class="form-control" 
           id="trailer" [(ngModel)]="editMovie.trailer" />
</div>

The two-way binding defined by [(ngModel)] takes the value of the component's property and assigns it as the default. As the user makes any change to the value, that value is then modified in the component's property, basically keeping the input element and component property in sync.

Also, according to this: https://developer.mozilla.org/en-US/docs/Web/HTML/Element/label

... the label for is expecting to match an input element's id property, not the name property. I also changed that above.

Share:
16,657
Stephen Agwu
Author by

Stephen Agwu

Want to hear a really good joke? Ok, so... wait, this is neither the time nor place. Back to code!!

Updated on June 13, 2022

Comments

  • Stephen Agwu
    Stephen Agwu almost 2 years

    I'm having trouble setting the value of a template driven form input. The value is coming from an editMovie object. I want the form to be filled with the editMovie values when shown and the user can then edit a part of the editMovie object or leave it the same. The form value is being set correctly for inputs that don't have [(ngModel)] attachted to them but the one's that do won't set a default value. Here is an example:

    <div class="form-group">
        <label for="imdb">Edit IMDb ID</label>
        <input #editImdb type="text" class="form-control" name="imdb" [(ngModel)]="editReviewForm.imdb" [value]="editMovie.imdb" required="" />
        <div class="mt-1" style="color:red">
            *required
        </div>
    </div>
    
    <div class="form-group">
        <label for="trailer">Edit Youtube Trailer</label>
        <input #editTrailer type="text" class="form-control" name="trailer" value="{{ editMovie.trailer }}" />
    </div>
    

    The first one doesn't work while the second one does. Following SO questions here I tried putting the value property in a two way data binding like this: [(value)] but that didn't work. Following this SO question I tried [ngValue] but this threw a parse error in the browser Can't bind to 'ngValue' since it isn't a known property of 'input'

    Does anybody know how to bind the value for a template driven form input?