角度 4 - ngModelChange 抛出无法读取属性 '...'在两个选择表单绑定期间未定义



>我有以下 json 模型,并希望有两个选择表单(下拉列表(,其中第一个下拉列表将包含标题,而第二个下拉列表包含作者的值取决于要选择的标题(第一个标题有两个,第二个有三个(。

 {
        "id": 1,
        "title": "bookA",
        "authors": [
            "authorA",
            "authorB"
        ]
},
 {
        "id": 2,
        "title": "bookB",
        "authors": [
            "authorA",
            "authorB",
            "authorC"
        ]
},

我对 Angular 4 相当陌生,但在搜索之后,我在 html 中提出了以下代码:

        <div class="form-group row">
            <label for="bookTitleField" class="col-sm-2 col-form-label">Title</label>
            <div class="col-sm-2">
                <select [(ngModel)]="currentInput.book.id" name="bookTitle" 
                (ngModelChange)="selectedBook=$event.target.value">
                    <option *ngFor="let b of books | async" value="{{b.id}}">{{b.title}}</option>
                </select>
            </div>
            <label for="bookAuthorField" class="col-sm-2 col-form-label">Author/label>
            <div class="col-sm-4">
                <select [(ngModel)]="currentInput.book.authors" *ngIf="currentInput.book.id" name="author">
                    <option *ngFor="let a of selectedBook" value="{{a.authors}}">{{a.authors}}</option>
                </select>
            </div>
        </div>

第一个下拉列表按预期工作,但是当单击第二个下拉列表时,会抛出错误:

ERROR TypeError: Cannot read property 'value' of undefined

代码的哪一部分不正确?

模板

undefined的是target。您可能希望使用 $event.id 从第一个下拉列表中获取 id 值。此外,您希望使用 [ngValue] 在第一个下拉列表中绑定整个对象,以便可以在下一个下拉列表中显示作者。因此,请将您的代码修改为如下所示的内容:

<select [(ngModel)]="chosenBook" name="bookTitle" (ngModelChange)="selectedBook.id = $event.id">
   <option *ngFor="let b of books | async" [ngValue]="b">{{b.title}}</option>
</select>
<label>Author</label>
<select [(ngModel)]="selectedBook.author">
  <option *ngFor="let a of chosenBook.authors">{{a}}</option>
</select>

另外,请记住初始化selectedBookchosenBook,以免收到undefined错误。

堆栈闪电战

你的代码应该可以工作,但现在很难说。另一种方法是使用如下所示的函数,

<div *ngIf="books">              //added this condition
        <select [(ngModel)]="currentInput.book.id" name="bookTitle" 
                (ngModelChange)="setValue($event)">
</div>
setValue(model){
  this.selectedBook=model.target.value;
}

最新更新