問題

我正在執行Angular 8 Web應用程式,有一些邏輯如下: HTML:

 <div *ngFor="let item of selectedItems;">
  <input type="radio"
         [(ngModel)]="mySelectedItem"
         [value]="item.key"
         (ngModelChange)="setChangedItem($event)"
  />
  {{item.name}}
</div>

<tr *ngFor="let additionalItem of additionalItems">
      <td>
        <input type="checkbox" [value]="myAdditional" [checked]="setAdditionalItems(additionalItem)">
      </td>
      <td>{{additionalItem.name}}</td>
      <td>
</tr>
 

當我更改單選按鈕時呼叫setAdditionalItems(這不是預期的).在component.ts檔案中找到

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

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent  {
  name = 'Angular';

  //additionalItems: any[]=[];
  myAdditional='';
  primaryItemType: any[]=[];
  arrayStuff: any[]=[];

  selectedItems = [
    {name: 'FirstVal', key: 1, additionalInfo: 'The is first in the row'},
    {name: 'SecondVal', key: 2, additionalInfo: 'The is second in the row'},
  ];

  additionalItems = [
    {name: 'ThirdVal', key: 3, additionalInfo: 'The is third in the row'},
    {name: 'FourthVal', key: 4, additionalInfo: 'The is fourth in the row'},
    {name: 'FifthVal', key: 5, additionalInfo: 'The is fifth in the row'},
  ];

  mySelectedItem = this.selectedItems[0].key

  setAdditionalItems(additionalItem){
    console.log("ping!", additionalItem)
  }

  setChangedItem(changedItem){
    //some logic
    console.log('setChangedItem', changedItem)
    this.setTypeByItem(changedItem)
}

setTypeByItem(changedItem){
  this.primaryItemType = this.arrayStuff.filter(matchItem => {
    if(matchItem.key === changedItem){
      return matchItem.matchValue
    }
  });
  return this.primaryItemType
  }
}
 

我究竟做錯了什麼?我沒有看到對呼叫setChangedItemsetAdditionalItems的函式的任何其他呼叫.這可能是我程式碼中其他東西的結果,因為這個程式碼庫中的許多東西(不是我編寫的)緊密耦合.

Stackblitz https://angular-qsiqor.stackblitz.io/

  最佳答案

問題是您的[檢查]資料繫結指令.如果您想在單擊複選框時啟用方法,則需要(更改)指令.

這是Stackblitz.希望這對你有用,如果沒有,請告訴我.

https://stackblitz.com/edit/angular-qnhbsn

  相同標籤的其他問題

javascriptangular