【发布时间】:2017-08-18 20:41:44
【问题描述】:
我正在使用一个父组件,该组件引用一个在 Angular 2 中播放音频文件的子组件。最初,我向音频文件传递了一个 _audioState 的输入变量,其中包含一个字符串值“Listen”。单击音频按钮时,该值将更改为“正在播放”,然后在音频文件播放完毕后更改为“重播”。这些字符串值更改发生在音频子组件中。
当在父组件中单击具有 nextAudio 功能的按钮时,我想将 _audioState 重新分配回“Listen”,但是一旦子组件更改此值,输入绑定在父组件中不起作用。
我仍在学习 Angular 2,并不确定实现此功能的最佳方法。我很感激任何建议。我的代码如下。
父组件:
@Component({
selector: 'parent-component',
template: ' <div>
<button (click)="nextAudio()"></button>
<audio-button [audioPath]="_audioPath"
[audioSrc]="_audioCounter" [audioState]="_audioState">
</audio-button>
</div>',
styleUrls: ['./parent-component.less']
})
export class ParentComponent {
_audioPath: string = "../audio/";
_audioCounter: number = 1;
_audioState: string = "Listen";
nextAudio(): void{
this._audioCounter = this._audioCounter + 1;
this._audioState = "Listen";
}
}
子组件:
@Component({
selector: 'audio-button',
template: '<button (click)="playSound()"><i class="fa fa-volume-up"></i>
{{audioState}}</button>',
styleUrls: ['./audio-button.component.less']
})
export class AudioButtonComponent {
@Input() audioPath: string;
@Input() audioSrc: string;
@Input() audioState: string;
playSound(): void {
let sound: any = new Audio(this.audioPath + this.audioSrc + ".mp3");
sound.play();
this.audioState = "Playing";
sound.addEventListener('ended', () => {
this.audioState = "Replay";
}, false)
event.preventDefault();
}
}
【问题讨论】: