Angular 2 - @Input未更新的嵌套组件

时间:2016-09-09 07:57:26

标签: angular typescript angular2-template

The Logic by IMG 我需要子组件变量来实时更新。 我试过@Input但它只是初始化而且不会随着时间的推移而改变。

父组件

<div>
    <h4>Рэйтынг : {{video.starRating}}</h4>
    <star-rating 
        [rating]="video.starRating" 
        (ratingChanged)="onRatingChanged($event)">
    </star-rating>
</div>

子组件

   @Component({
        selector: 'star-rating',
        templateUrl: 'app/shared/star-rating.component.html',
        styleUrls:['app/shared/star-rating.component.css'],
        inputs:['rating']
   })
   export class StarRatingComponent implements OnInit,OnChanges {

     rating: number;
     @Output() ratingChanged = new EventEmitter<number>();

     ngOnChanges(changes: {[propKey: string]: SimpleChange}) {

        for (let propName in changes) {
            let changedProp = changes[propName];
           if(changedProp == "rating"){
               this.calcStarRating();
               console.log("rating = "+this.rating);
               console.log("ratingCurr = "+changedProp.currentValue);
               console.log("ratingPrev = "+changedProp.previousValue);
           }
        }
    }

    onStarClicked(item: number) {
        this.ratingChanged.emit(item + 1);
    }

    calcStarRating() {
        ...calc logic....
        console.log(this.rating)
    }

    ngOnInit() {
        this.calcStarRating();
    }
  }

视频

export class Video{
    videoId:string;
    videoTitle:string;
    price: number;
    description: string;
    starRating: number;
    imageUrl: string;
}

父逻辑

  export class VideoDetailComponent implements OnInit ,OnDestroy{

    video:Video;

    private sub: Subscription;

    ngOnInit() {
        this.sub = this._routeParams.params.subscribe(params=>{
            if(params && params['id']){
                this.sub1 =  this._vs.getItemById(params['id'])
                    .subscribe(t=>this.video = t);
            }
        });
    }

    onRatingChanged(rating:number){
        if(this.video.starRating!=0){
            this.video.starRating +=rating;
            this.video.starRating /= 2;
        }
        else this.video.starRating = rating;

        this.video.starRating = +this.video.starRating.toFixed(2);
        this._vs.updateItem(this.video);
    }

    onBack(){
        this.router.navigate(['/list']);
    }


    constructor(private _routeParams: ActivatedRoute,
                private _vs:VideoService,
                private router: Router) {

    }
  }

我记录了评分,没有任何事情发生。我递增\递减值。父模型已更改,但更改不会通过@input发送给子项。问题是如何实时绑定。是否可以使用@Input或我需要使用一些Observable / Events e.t.c

感谢阅读:)

1 个答案:

答案 0 :(得分:1)

它有效,但您似乎对if(changedProp == "rating"){...}行有问题,因为您正在匹配/比较对象字符串

您需要将其更改为if(propName == "rating"){...}

这将解决问题。