Raphael Castro
Raphael Castro

Reputation: 59

how do I implement template variables in angular?

Im trying to pull the ngModel object for form validation but upon serving I'm getting an error at my template variable.

here is the code:

<form>
    <div class="form-group">
        <label for="courseName">Course Name</label>
        <br />
        <input type="text" id="courseName" ngModel name="courseName" #courseName="ngModel" required />
        <br />
        <div *ngIf="!courseName.valid" class="alert alert-danger">field is required</div>
        <label for="category">Category</label>
        <br />
        <select name="category" id="category" class="form-control-lg" ngModel>
            <option value="test">poop</option>
        </select>
        <div class="checkbox">
            <label for="checkbox">
                <input id="checkbox" type="checkbox" name="moneyBack" />30-day money back guarantee
            </label>
        </div>
    </div>
    <button class="btn btn-primary">Submit</button>
</form>

EDIT
After testing, I found that the problem arises when I assign the template variable, as well as I noticed that the "#" symbol in my code editor is not the same color as the tutorial I'm watching meaning that the editor isn't recognizing the syntax so its possible that this syntax is either deprecated (which is possible, the tutorial I'm following seems to be a little older) or I am implementing it wrong, what is the correct way to declare a template variable?

OR more importantly lol

what is the correct way to access the form-control object so I can get the .value, .pristine, .touched properties?

<#templateVariable ngModel name="test"> **No Error**
<#templateVariable="ngModel" ngModel name="test>**ERROR**

EDIT

EDIT
The issue was with naming ngModel and the field the same same
EDIT

here is a screenshot of the error
here is a screenshot of the import of ngModel

Upvotes: 0

Views: 133

Answers (2)

FC94
FC94

Reputation: 48

There are few things that you can check:

  1. Import FormModule in app.module.ts file.

  2. Change your code in the following way

    <input type="text" id="courseName"  [(ngModel)] = "courseName" name="courseName" #course="ngModel" required/>
    
  3. [(ngModel)] and reference name must be different. If you put both same name to 'courseName' you will get reference error!

Upvotes: 1

dasunse
dasunse

Reputation: 3079

Use this way

[(ngModel)]="courseName"

Upvotes: 1

Related Questions