Angular - Uncaught Error: Cannot assign to a reference or variable

594 Views Asked by At

I have an Angular 8 app.

app.component.html

 <div>
    <label class="form-check-label f-14">
       <input type="checkbox" class="form-check-input" name="isAgree" [(ngModel)]="isAgree" #isAgree="ngModel"/> Agree?
    </label>
 </div>

But this is throwing the error.

compiler.js:7627 Uncaught Error: Cannot assign to a reference or variable! at _AstToIrVisitor.visitPropertyWrite (compiler.js:7627)

I want to understand this error definition & cause. How can I get rid of this?

Also, I don't want to declare any variable in my app.component.ts. I need to access the isAgree flag value in view. So ideally I was trying as below.

<div>
    <label class="form-check-label f-14">
       <input type="checkbox" class="form-check-input" name="isAgree"  #isAgree/> Agree?
    </label>
    <p> {{isAgree}} </p> 
 </div>

But the value is not reflecting.

How can I get the value in this way?

I know I am combining 2 questions but both seem very relevant. Hence did so.

Thanks!

2

There are 2 best solutions below

0
On
 <div>
    <label class="form-check-label f-14">
       <input type="checkbox" class="form-check-input"  [(ngModel)]="isAgree" #isAgree.value="ngModel"/> Agree?
    </label>
 </div>
<div>

Above code will work fine.

#isAgree refers to the input element. you have to bind to its value property #isAgree.value="ngModel

0
On

The error message you're getting is because you're trying to assign a variable isAgree in the template which has already been defined in the component.

The following is all you need as long as you have the property isAgree in your component. The two way binding using [(ngModel)] will ensure this property is updated whenever the input value changes (and vice versa):

<div>
  <label class="form-check-label f-14">
    <input type="checkbox" class="form-check-input" name="isAgree" [(ngModel)]="isAgree"/>
    Agree?
  </label>
  <p>{{isAgree}}</p> 
</div>