未捕获错误:无法分配给参考或>变量! > at _AstToIrVisitor.visitPropertyWrite

时间:2018-03-18 22:21:12

标签: angular typescript

我正在关注angular.io网站上的一个例子,该网站使用输入创建一个带角度的表单,但我遇到了错误:

  

compiler.js:26390未捕获错误:无法分配给引用或   变量!       at _AstToIrVisitor.visitPropertyWrite(webpack-internal:///./node_modules/@angular/compiler/esm5/compiler.js:26611:23)       在PropertyWrite.visit(webpack-internal:///./node_modules/@angular/compiler/esm5/compiler.js:4900:24)       在convertActionBinding(webpack-internal:///./node_modules/@angular/compiler/esm5/compiler.js:26035:45)       在eval(webpack-internal:///./node_modules/@angular/compiler/esm5/compiler.js:28635:22)       在Array.forEach()       在ViewBuilder._createElementHandleEventFn(webpack-internal:///./node_modules/@angular/compiler/esm5/compiler.js:28631:18)       at nodes。(匿名函数)(webpack-internal:///./node_modules/@angular/compiler/esm5/compiler.js:28050:27)       在eval(webpack-internal:///./node_modules/@angular/compiler/esm5/compiler.js:28576:22)       在Array.map()       在ViewBuilder._createNodeExpressions(webpack-internal:///./node_modules/@angular/compiler/esm5/compiler.js:28575:56)

我所做的唯一改变是重命名"名称"到"用户名"。

dashboard.component.ts

import { Component, OnInit } from '@angular/core';

@Component({
  selector: 'app-dashboard',
  templateUrl: './dashboard.component.html',
  styleUrls: ['./dashboard.component.css']
})
export class DashboardComponent implements OnInit {

  username: string;
  submitted = false;

  constructor() { 
  }

  ngOnInit() {
  }

  onSubmit() { this.submitted = true; }

}

dashboard.component.html

<div class="row justify-content-md-center">
    <div class="col col-lg-12">
      <form (ngSubmit)="onSubmit()" #usernameForm="ngForm" >
        <div class="form-group">
          <label for="username">Name</label>                    

          <input type="text" class="form-control" id="name"
          required
          [(ngModel)]="username" name="name"
          #username="ngModel">

          <div [hidden]="username.valid || username.pristine"
              class="alert alert-danger">
            Name is required
          </div>
        </div>
        <button type="submit" class="btn btn-success">Submit</button>
      </form>
    </div>
</div>

上述代码有什么问题?

1 个答案:

答案 0 :(得分:12)

你的问题在这里:

[(ngModel)]="username" name="name"
      #username="ngModel">

执行此操作时,您需要为模板创建变量username,该变量引用NgModel实例。因此,当您将ngModel绑定到username时,编译器会认为您已绑定到引用,而不是绑定到组件的username属性,因为模板变量会隐藏组件属性同名。将引用的名称更改为usernameModel或类似的内容(并记住在您使用它的任何地方更改它,就像显示错误的div一样)它应该可以正常工作