我使用单选按钮对星形输入进行了评级。我可以完美地添加这个评级,但是当我想在页面上显示它或编辑时它显示我只有1(1开始突出显示为5)即使评级为5.我理解角度将评级仅限于1星。我怎样才能将它正确地绑定到所有的星星上?
HTML:
<div class="form-group">
<label for="">Rating</label>
<fieldset>
<span class="star-cb-group">
<input type="radio" id="rating-5" name="rating" [value]=book.rating [(ngModel)] = "book.rating" #r="ngModel"/><label for="rating-5">5</label>
<input type="radio" id="rating-4" name="rating" [value]=book.rating [(ngModel)] = "book.rating" #r="ngModel"/><label for="rating-4">4</label>
<input type="radio" id="rating-3" name="rating" [value]=book.rating [(ngModel)] = "book.rating" #r="ngModel"/><label for="rating-3">3</label>
<input type="radio" id="rating-2" name="rating" [value]=book.rating [(ngModel)] = "book.rating" #r="ngModel"/><label for="rating-2">2</label>
<input type="radio" id="rating-1" name="rating" [value]=book.rating [(ngModel)] = "book.rating" #r="ngModel"/><label for="rating-1">1</label>
</span>
<div class="alert alert-danger"
*ngIf="r.invalid">
Rating is required
</div>
</fieldset>
</div>
单击edit
按钮将数据上传到数据库时,将调用下面的submit
函数。
edit(book) {
const id = this.activeRoute.snapshot.params['id'];
const updbook = {
_id: id,
title: book.title,
author: book.author,
description: book.description,
status: book.status,
displayStatus: book.displayStatus,
rating: book.rating
};
console.log(book);
//
this.bookService.editBook(updbook).subscribe(data => {
if (data.success) {
console.log('book edited');
this.router.navigate(['/']);
} else {
console.log('error book edit');
}
});
}
答案 0 :(得分:1)
为多个单选按钮name
属性指定相同的名称时,它们将变为radio-button-group
,并且只能将其中一个设置为已选中。尝试使用不同的名称绑定到name
属性。
我建议您使用checked
属性设置单选按钮的状态,并使用click
或change
事件来设置rating
。
<input type="radio" [checked]="rating >= 1" (click)="rate(1)">
<input type="radio" [checked]="rating >= 2" (click)="rate(2)">
<input type="radio" [checked]="rating >= 3" (click)="rate(3)">
<input type="radio" [checked]="rating >= 4" (click)="rate(4)">
<input type="radio" [checked]="rating >= 5" (click)="rate(5)">
rate(val) {
// here setTimeout or ChangeDetectorRef.markForCheck will let angular rerender the page according to changes of value
setTimeout(() => {
this.book.rating = val;
});
}
<强> Plunker Demo 强>