Я хочу изменить и сохранить рейтинг каждого модуля star-rating в переменной в угловых значениях 2 - PullRequest
0 голосов
/ 20 февраля 2019

Я хочу выбрать рейтинг каждой звезды в независимых переменных, что поможет мне сохранить значения в API создания, для каждой звезды должно быть уникальное значение.
Вот мой starrating.component.ts файл -

import {
    Component,
    OnInit,
    Input,
    Output,
    EventEmitter,
    ViewEncapsulation
} from '@angular/core';
import { MatSnackBar } from '@angular/material';

@Component({
    selector: 'mat-star-rating',
    templateUrl: './starrating.component.html',
    styleUrls: ['./starrating.component.css'],
    encapsulation: ViewEncapsulation.Emulated
})
export class StarRatingComponent implements OnInit {

    @Input('rating') private rating: number = 3;
    @Input('starCount') private starCount: number = 5;
    @Input('color') private color: string = 'accent';
    @Input('ratingID') private ratingID: number = 0;
    @Output() private ratingUpdated = new EventEmitter<{ rating: number, ratingID: number }>();

    private snackBarDuration: number = 2000;
    private ratingArr = [];

    constructor(private snackBar: MatSnackBar) {}

    ngOnInit() {
        console.log("a " + this.starCount)
        for (let index = 0; index < this.starCount; index++) {
            this.ratingArr.push(index);
        }
    }

    onClick(rating: number, ratingID: number) {
        console.log(rating)
        this.snackBar.open('You rated ' + rating + ' / ' + this.starCount,
            '', {
                duration: this.snackBarDuration
            });
        this.ratingUpdated.emit({ rating, ratingID });
        return false;
    }

    showIcon(index: number) {
        if (this.rating >= index + 1) {
            return 'star';
        } else {
            return 'star_border';
        }
    }
}

export enum StarRatingColor {
    primary = "primary",
        accent = "accent",
        warn = "warn"
}

ниже - starrating.component.html , куда я положил свой HTML-код -

<button mat-icon-button [color]="color" *ngFor="let ratingId of ratingArr;index as i" 
    [id]="'star_'+i" (click)="onClick(i+1)" [matTooltip]="ratingId+1" matTooltipPosition="above">
    <mat-icon>
        {{showIcon(i)}}
    </mat-icon>
</button>
<mat-error *ngIf="starCount == null || starCount == 0">
    Star count is <strong>required</strong> and cannot be zero
</mat-error>
<p class="body-2">
    Your rated <span class="body-2">{{rating}}</span> / <span class="body-2">{{starCount}}</span>
</p>

Теперь яиспользуйте этот компонент в моем компоненте обратной связи с помощью селектора и хотите сохранить значения, когда пользователи присваивают оценку каждой звезде, через мой файл feedback.component.html, который я показываю пользователям в браузере.Ниже мой feedback.component.ts -

import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
import { FormBuilder, FormGroup, Validators } from '@angular/forms';
import { StarRatingComponent } from '../../components/starrating/starrating.component';
import { JsonPipe } from '@angular/common';
import { StarRatingColor } from '../../components/starrating/starrating.component';

@Component({
    selector: 'feedback-form',
    styleUrls: ['./feedbackform.component.css'],
    templateUrl: './feedbackform.component.html',
    providers: []
})

export class FeedbackFormComponent implements OnInit {
    rating: number = 3;
    starCount: number = 5;
    starColor: StarRatingColor = StarRatingColor.accent;
    starColorP: StarRatingColor = StarRatingColor.primary;
    starColorW: StarRatingColor = StarRatingColor.warn;

    inputName: string;
    isLinear = false;
    firstFormGroup: FormGroup;
    secondFormGroup: FormGroup;
    answer: string;
    constructor(private _formBuilder: FormBuilder) {}
    ngOnInit(): void {
        this.firstFormGroup = this._formBuilder.group({
            firstCtrl: ['', Validators.required]
        });
        this.secondFormGroup = this._formBuilder.group({
            secondCtrl: ['', Validators.required]
        });
    }

    onRatingChanged(rating) {
        console.log(rating);
        this.rating = rating;
    }
}

и ниже, наконец, мой файл feedbackcomponent.html -

<mat-step [stepControl]="firstFormGroup">
    <p>Was there any problem?</p>
    <form [formGroup]="firstFormGroup">
        <ng-template matStepLabel>Problem ?</ng-template>
        <mat-form-field>
            <input matInput placeholder="answer" formControlName="firstCtrl" required>
        </mat-form-field>
        <div>
            <button mat-button matStepperNext>Report
                Quality</button>
        </div>
    </form>
</mat-step>

Когдаиспользуя его, мой щелчок мышью по звездочке изменяет значение каждой звезды, но я хочу изменить значение конкретной звезды по своему выбору и сохранить их в переменной ... помогите

...