In my code, I have a component that holds all the data retrieved from firebase. Including a variable called "currentTurnName" which gets passed from the parent to the child component. That variable is used to render a twitch channel inside the child component but doesn't update when the data changes.. I followed a few stack overflow guide that talk about using the *ngIf directive like <childComponent *ngIf"currentTurnName"> to stop the child component from loading until the data is retrieved- it works on page load, except it doesn't work when that variable is passed in new data asynchronously.
Child Component
export class TwitchVideoComponent implements OnInit {
constructor() {
}
player: any;
@Input() currentTurnName: any;
ngOnInit(): void {
var options = {
width: 1080,
height: 720,
channel: this.currentTurnName,
};
this.player = new Twitch.Player("<player div ID>", options)
this.player.setVolume(0.5);
console.log(this.currentTurnName);
}
// ngOnChanges(changes: SimpleChanges) {
// if (this.currentTurnName) {
// this.player.setChannel(this.currentTurnName);
// }
// }
}
Child Template
<div id="<player div ID>" class="twitch"></div>
Parent component
export class GameRoomComponent implements OnInit {
public users$: Observable<User[]>
currentUser: Observable<CurrentUser[]>;
constructor(private usersService: UsersService, private afs: AngularFirestore) {
this.currentTurn = afs.collection<CurrentUser>('currentPlayerDB').valueChanges().pipe(
tap(res => {
this.currentTurnName = res[0].user;
console.log(this.currentTurnName);
})
).subscribe();
}
currentTurn: any;
items: any;
currentTurnName : any;
Parent Template
<app-twitch-video *ngIf="currentTurnName" [currentTurnName]="currentTurnName" >
This somewhat talks about my issue, but mine is more complex considering the data is changed Angular 2 child component loads before data passed with @input()
You could use Angular's property setters. The documentation can be found here in this section (Intercept input property changes with a setter): https://angular.io/guide/component-interaction
Here is a snippet using your code:
export class TwitchVideoComponent implements OnInit {
constructor() {}
player: any;
@Input() set currentTurnName(name) {
this._currentTurnName = name;
console.log('This should fire every time this Input updates', this._currentTurnName);
if (this._currentTurnName) {
this.player.setChannel(this._currentTurnName);
}
}
public _currentTurnName: any;
ngOnInit(): void {
var options = {
width: 1080,
height: 720,
channel: this._currentTurnName,
};
this.player = new Twitch.Player("<player div ID>", options)
this.player.setVolume(0.5);
console.log(this._currentTurnName);
}
}
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.