【发布时间】:2020-12-04 09:08:06
【问题描述】:
我的应用程序架构主要基于输出和输入。一切正常,直到我偶然发现这个问题:我有一个动态组件,用户可以在其中写电影评论,但是我发送给负责与 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!');
}
}
reviews 组件的 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: ['', Validators.required],
});
}
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();
}
任何帮助将不胜感激!
【问题讨论】:
-
你能分享我的应用审查模板吗? - @Mellville
标签: angular output eventemitter