[英]Angular 4 - Calling a parent method from a child component not working
我的所有事件發射器都正常工作,除了一個。
child.ts:
@Component({
...
outputs: ['fileUploaded']
})
export class childComponent implements OnInit {
...
fileUploaded = new EventEmitter<boolean>();
...
randomMethod(){
...
this.fileUploaded.emit(true);
}
}
從父組件調用randomMethod(),我將在parent.ts中顯示。 它不是在child.html中調用的。
parent.html
...
<child (fileUploaded)="onSubmit($event)"></child>
..
parent.ts
export class parentComponent {
...
theChild = new childComponent;
submitted = false;
...
onSubmit(event: boolean) {
console.log('in onSubmit()');
this.submitted = event;
}
functionCallsChild(){
this.theChild.randomMethod();
...
this.theChild = new childComponent;
}
}
我的應用程序從不記錄“在onSubmit()”中,為什么不調用此方法? 我也嘗試不在我的最后一行創建一個新的子對象,但這並沒有什么區別。
也許我不清楚為什么你選擇這種方法或你需要它,但據我所知,你應該使用從孩子到其父母的EventEmitter
。 這意味着將觸發.emit()shold的事件放在child.html中。 嘗試這樣做,它應該工作:
child.html
<div (click-or-whatever-fires-what-you-want)="randomMethod()"></div>
child.ts:
@Component({
...
})
export class childComponent implements OnInit {
...
@Output() fileUploaded = new EventEmitter<boolean>();
...
randomMethod(){
...
this.fileUploaded.emit(true);
}
}
parent.html
...
<child (fileUploaded)="onSubmit($event)"></child>
..
parent.ts
export class parentComponent {
...
submitted = false;
...
onSubmit(event: boolean) {
console.log('in onSubmit()');
this.submitted = event;
}
}
希望它有所幫助。
您可以使用@Output發射器從子組件調用父組件的方法,該發射器將觸發子組件上的任何事件。 我在評論部分使用這種方法來使用子組件的方法更新父組件中的計數。
Parent.ts
/** Update the count from child component */
UpdateCount(id) {
this.getTotalCommentCountByGroupId(id);
}
Parent.HTML
<srv-group-feed [LiveFeedInput]="groupPostRes"
(CommentCount)="UpdateCount($event)"></srv-group-feed>
Child.ts
this.CommentCount.emit(data you need to pass);
在全局范圍內,您可以在子組件中聲明@Output事件,即child.ts
@Output() CommentCount = new EventEmitter<string>();
試試這種方式:
@Output()
fileUploaded = new EventEmitter<boolean>();
並刪除:
outputs: ['fileUploaded']
在這里檢查文檔! :d
您不應該使用new運算符創建子組件。
您應該使用@ViewChild()
來引用子組件。
您選擇的子組件是錯誤的,您應該像這樣使用ViewChild
:
parent.html:
<child #theChild (fileUploaded)="onSubmit($event)"></child>
parent.ts:
export class parentComponent {
...
@ViewChild('theChild') theChild;
submitted = false;
...
onSubmit(event: boolean) {
console.log('in onSubmit()');
this.submitted = event;
}
functionCallsChild(){
this.theChild.randomMethod();
...
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.