问题描述
我的应用程序体系结构主要基于输出和输入。一切正常,直到我偶然发现了这个问题:我有一个动态组件,用户可以在其中编写电影的评论,但是我发送给负责与API通信的组件的对象没有收到任何东西,因此我无法找出原因。是因为动态创作吗?这是代码
将评论发送到API的组件的HTML
<div *ngIf="movie">
<div *ngFor="let m of movie">
Details of {{m.Title}}
</div>
<button (click)="createReview()" mat-raised-button color="primary">Write your own review!</button>
<template #usersreview>
<app-reviews [movie]="movie" (sendCreds)="credentialsReceived($event)"></app-reviews>
</template>
</div>
TS:
export class RightMovieComponent implements OnInit {
@input() movie:any[]
@ViewChild('usersreview',{ read: ViewContainerRef,static: false }) container;
componentRef: ComponentRef<any>
constructor(private location:Location,private resolver: ComponentFactoryResolver) { }
ngOnInit(): void {
}
createReview(){
this.container.clear();
const factory: ComponentFactory<any> = this.resolver.resolveComponentFactory(ReviewsComponent);
this.componentRef = this.container.createComponent(factory);
this.componentRef.instance.movie = this.movie;
}
credentialsReceived(review:any) {
console.log(review); -----> nothing on the console,no errors,nothing
//this.componentRef.destroy(); --->commented
alert('review submited!');
}
}
评论组件的TS
@input() movie: any[];
@Output() sendCreds: EventEmitter<any> = new EventEmitter<any>();
user: User;
reviewForm: FormGroup;
movieTitle:any;
constructor(private auth: AuthService,private fb: FormBuilder) {
this.auth.currentUser.subscribe((user) => (this.user = user));
}
ngOnInit(): void {
this.reviewForm = this.fb.group({
title: ['',Validators.required],body: ['',});
}
get title() {
return this.reviewForm.get('title');
}
get body() {
return this.reviewForm.get('body');
}
onSubmit() {
if (this.reviewForm.invalid) return;
this.movieTitle = this.movie.map((t) => t['Title']);
let credentials = {
author: this.user.username,title: this.title.value,body: this.body.value,movieTitle: this.movieTitle[0],};
this.sendCreds.emit({creds:credentials}); ------>here the the object is displayed on the console
this.reviewForm.reset();
}
任何帮助将不胜感激!
解决方法
动态创建组件时,您需要定义与事件发射器的通信(就像您定义与输入的通信一样):
this.componentRef.instance.sendCreds.subscribe(event => // do whatever);