2017-10-17 22 views
0

我正在準備調查問卷。我已經創建了一個星級組件給予評級,問題是我如何將這個星級值鏈接到特定的問題。這是我到現在爲止所做的。如何將選中的值鏈接到數組中的特定對象

這裏越來越輸出

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

} 

我的應用程序組件是

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

所有你需要做的是通過問題的id明星通過@Input並在用戶更改時獲取它評級,

請看看:


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> 
... 
+0

大其工作TQ。 –

+0

Gald,它對你有幫助,你也請提出答案@Urock? –

相關問題