我正在使用一个父组件,该组件引用在Angular 2中播放音频文件的子组件。最初,我传递的音频文件是_audioState的输入变量,其中包含字符串值“Listen”。单击音频按钮时,此值将变为“正在播放”,然后在播放完音频文件后再“重播”。这些字符串值更改发生在audio子组件中。
当在父组件中单击具有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();
}
}
答案 0 :(得分:1)
有几种方法可以做到,包括
参考
Adding Redux with NgRx/Store to Angular (2+) – Part 1(Oren Farhi)
例如,
@Component({
selector: 'parent-component',
template: `<div>
Current state : {{_audioState}}
<hr />
<audio-button [audioPath]="_audioPath"
[audioSrc]="_audioCounter" [audioState]="_audioState"
(emit-status)="updateStatus($event)"
>
</audio-button>
</div>`
})
export class ParentComponent {
_audioPath: string = "../audio/";
_audioCounter: number = 1;
_audioState: string = "Listen";
nextAudio(): void{
this._audioCounter = this._audioCounter + 1;
this._audioState = "Listen";
}
private updateStatus(status:string){
this._audioState= status;
}
}
import { Component, OnInit, Input, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'audio-button',
template: `<button (click)="playSound()"><i class="fa fa-volume-up"></i>
{{audioState}}</button>`,
})
export class AudioButtonComponent {
@Input() audioPath: string;
@Input() audioSrc: string;
@Input() audioState: string;
@Output('emit-status') emitStatus = new EventEmitter<any>();
playSound(): void {
//...
//emit data to parent
this.emitStatus.emit("playing");
}
}
@Component({
selector: 'parent-component',
template: `<div>
Current state : {{audioBtn.audioState}}
<hr />
<audio-button [audioPath]="_audioPath"
[audioSrc]="_audioCounter" [audioState]="_audioState"
(emit-status)="updateStatus($event)"
>
</audio-button>
</div>`
})
export class ParentComponent {
@ViewChild(AudioButtonComponent) audioBtn: AudioButtonComponent;
}
export class AudioButtonComponent {
//...
@Input() audioState: string;
playSound(): void {
//...
this.audioState = "playing";
}
}