【发布时间】:2020-09-06 04:15:04
【问题描述】:
我正在做一个有角度的项目,我在 for 循环中有一个表单:
这是我的 Angular html 代码:
<ul class="border">
<li *ngFor="let cake of cakes; let idx = index">
<img class="d-inline-block" src="{{cake.url}}" alt="{{cake.id}}" width="250" height="250">
<form class="d-inline-block form-rate">
<div class="form-group">
<select name="stars" [(ngModel)]="newRate.stars" class="custom-select">
<option selected value="1">1 stars</option>
<option value="2">2 stars</option>
<option value="3">3 stars</option>
<option value="4">4 stars</option>
<option value="5">5 stars</option>
</select>
</div>
<div class="form-group">
<textarea name="comment" [(ngModel)]="newRate.comment" class="form-control" id="rate-comment" rows="4"
placeholder="Type your comment here"></textarea>
</div>
<div class="form-group clearfix">
<button class="btn btn-primary float-right btn-sm" (click)="ratingSubmit(cake._id)">Rate!</button>
</div>
</form>
</li>
</ul>
每当我输入 textarea 或以该表单选择一个值时,它都会在该 ul 中执行相同的操作。如何解决这个问题?
这是我的打字稿文件,用于在 html 中显示对象和数组。
export class RateSubmitComponent implements OnInit {
cakes = [];
cake = "";
rates = [];
rate = "";
newCake: any;
newRate: any;
constructor(private _httpService: HttpService) {}
ngOnInit() {
this.getCakesFromService();
this.newCake = { name: "", url: "" };
}
getCakesFromService() {
let observable = this._httpService.getCakes();
observable.subscribe((data) => {
this.cakes = data["data"];
});
}
getRatesFromService() {
let observable = this._httpService.getRates();
observable.subscribe((data) => {
this.rates = data["data"];
});
}
onSubmit() {
let observable = this._httpService.addCake(this.newCake);
observable.subscribe((data) => {
this.newCake = { name: "", url: "" };
this.getCakesFromService();
});
}
ratingSubmit(cakeId) {
let observable = this._httpService.addRating(this.newRate, cakeId);
observable.subscribe((data) => {});
this.newRate = { stars: "", comment: "" };
this.getRatesFromService();
}
}
【问题讨论】: