我正在准备一份小调查问卷。我创建了一个星级组件来给出评级,问题是如何将这个星级值链接到特定问题。这是我到现在为止所做的。
这是获得输出
我的明星组件是
@Component({
selector: 'app-star',
template: `<div class="rating">
<input type="radio" value="3" [checked]="rating===3" /> <label (click)='onClick(3)'></label>
<input type="radio" value="2" [checked]="rating===2" /> <label (click)='onClick(2)'></label>
<input type="radio" value="1" [checked]="rating===1" /> <label (click)='onClick(1)'></label>
</div><br><br>
<h1 *ngIf="ratbool == true">Your rating is :{{rating}}</h1>`,
styleUrls: ['./star.component.css']
})
export class StarComponent {
@Output() ratingno: EventEmitter<any> = new EventEmitter<any>();
rating: number;
ratbool: boolean = false;
ngOnInit() {
}
onClick(rating: number): void {
this.ratingno.emit(rating);
this.rating = rating;
this.ratbool = true;
}
}
我的app组件是
export interface type{
id:number;
text:string;
}
@Component({
selector: 'app-root',
template:`
<ul *ngFor="let sur of mySentences">
<li>{{sur.text}}</li> <app-star (ratingno)="doSomething($event)"></app-star>
</ul>
<button (click)="submit(mySentences)">submit</button>`,
styleUrls: ['./app.component.css'],
})
export class AppComponent {
rating:number;
mySentences:type[] = [
{id: 1, text: 'question 1'},
{id: 2, text: 'question 2'},
{id: 3, text: 'question 3'},
];
doSomething(rating){
this.rating=rating;
}
submit(j){
console.log(j);
}
}
答案 0 :(得分:1)
您需要做的就是通过@Input
将问题ID传递给星标,并在用户更改评分时获取
请看一下:
<强> star.component.ts 强>
export class StarComponent {
@Output() ratingno: EventEmitter<any> = new EventEmitter<any>();
@Input() question_id:Number;
rating:any;
.....
onClick(rating: number): void {
this.ratingno.emit({question_id , rating});
this.rating = rating;
this.ratbool = true;
}
}
<强> app.component.ts 强>
...
<li>{{sur.text}}</li> <app-star [question_id]='sur.id' (ratingno)="doSomething($event)"></app-star>
...