如何将选中的值链接到数组中的特定对象

时间:2017-10-17 07:59:02

标签: javascript json angular

我正在准备一份小调查问卷。我创建了一个星级组件来给出评级,问题是如何将这个星级值链接到特定问题。这是我到现在为止所做的。

这是获得输出

enter image description here

我的明星组件是

@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);
}
}

1 个答案:

答案 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>
...