在按钮上单击ngFor从ngFor获取对象,id和值

时间:2018-11-19 06:56:53

标签: angular angular5 angular6

这是html代码

<tr>
    <td>Select New Subject:</td>
    <td>
     <Select name="DesiredSubject" [(ngModel)] = "sub" ngDefaultControl>
       <option [value]="0">--Select Subject--</option>
       <option *ngFor ="let subj of subjects" [value]="subj">{{subj.bank_Name}}</option>
     </Select>
    </td>
  </tr>
  <tr>
    <td>Action :</td>
    <td><button value="Update Subject" (click)="changeSubject(sub)">Update Subject</button></td>
</tr>

这是我的打字稿角类

 export class EditSubjectComponent implements OnInit, AfterViewInit {

  @Input()
  subject : any;
  sub : any;
  flag : boolean = false;
  subjects : ISubject[];
  constructor(private _QuestionService : QuestionService, private _toastr : ToastrService) { }

  ngOnInit() {
  }
  ngAfterViewInit(){
      this._QuestionService.getSubject().subscribe((data) => {this.subjects = data;});
    }
  changeSubject(value : any){
    this.flag = true;
    console.log(value)
   this._QuestionService.updateSubject(QID,value).subscribe((res) => {this._toastr.success("Subject Changed");
  }, err => {
       this._toastr.error("There is some problem. Please try later")
     });
    this.flag = false;
  }

}

这就是控制台日志中显示的内容。我的意思是它正在返回一个字符串。

enter image description here

我在做什么错?我现在已经更新了代码。

1 个答案:

答案 0 :(得分:1)

问题是您将对象绑定到[value]属性。如果要将对象绑定到您的option值,请使用[ngValue]而不是[value]

您的html中也有一个实现select的错字。使用<select>代替<Select>

Stackblitz示例:https://stackblitz.com/edit/angular-3b5txx