错误:无法将值“$event”分配给模板变量 Angular 10

Tha*_*ong 11 angular

当我将值设置为时出现奇怪的错误p-dropdown

ERROR: Uncaught (in promise): Error: Cannot assign value "$event" to template variable "bed". Template variables are read-only.
Error: Cannot assign value "$event" to template variable "bed". Template variables are read-only.
    at _AstToIrVisitor.visitPropertyWrite (compiler.js:8348)
    at PropertyWrite.visit (compiler.js:7236)
    at convertActionBinding (compiler.js:7935)
    at prepareEventListenerParameters (compiler.js:16723)
    at Object.params (compiler.js:17822)
    at compiler.js:17599
    at Array.map (<anonymous>)
    at compiler.js:17599
    at compiler.js:16878
    at Array.map (<anonymous>)
    at resolvePromise (zone.js:1215)
    at resolvePromise (zone.js:1165)
    at zone.js:1277
    at ZoneDelegate.invokeTask (zone.js:407)
    at Object.onInvokeTask (core.js:27474)
    at ZoneDelegate.invokeTask (zone.js:406)
    at Zone.runTask (zone.js:179)
    at drainMicroTaskQueue (zone.js:583)
Run Code Online (Sandbox Code Playgroud)

如果我需要使用我该怎么做[(ngModel)]

HTML 代码:

<div class="col-12">
     <div *ngFor="let bed of local_bed">
        <p-dropdown [options]="bedType" formControlName="bedTypeID" [(ngModel)]="bed"></p-dropdown>
     </div>
</div>
Run Code Online (Sandbox Code Playgroud)

TS代码:

local_bed: any;
    
selectBedById(id: string) {
     this.roomService.queryRoomBedById(id).subscribe(res => {
         this.local_bed = res;
     });
 }
Run Code Online (Sandbox Code Playgroud)

时的值console.log是:

[ "3", "3", "1" ] 
Run Code Online (Sandbox Code Playgroud)

And*_*rei 22

原因是您创建了一个“局部”变量bed。您无法更改它,但您在传递到 时试图更改它ngModel。您可以像这样传递数组项:

<div *ngFor="let bed of local_bed; let i = index">
        <p-dropdown [options]="bedType" formControlName="bedTypeID" [(ngModel)]="local_bed[i]"></p-dropdown>
</div>
Run Code Online (Sandbox Code Playgroud)

表达式ngFor略有升级(包括let i = index),ngModel参数从 更改bedlocal_bed[i]


Rom*_*ene 5

您将模板变量和组件变量命名为相同。