[英]Button clicked does its function only once when it needs to do it for each item
[英]Angular 8 - Clicked button only does function() once
一個按鈕只執行一次該功能,視頻顯示問題: https : //vimeo.com/342491616
邏輯如下:當單擊'home'(在footer.component內)時,將函數發送到parent(app.component),然后將其發送到'hamburguer'按鈕(在header.component內)。
我已經讀過它可能是與ngOnChanges相關的東西,但是我用它試了好幾次但它沒有用,但也許我使用它錯了(?)
代碼在這里:
footer.component.html
<a (click)="sendMessage()" routerLink="/page"><img src="assets/images/homebutton.png" class="footer_buttons" id="home_button"></a>
footer.component.ts(在導出類中......)
message: string = "hamburguer";
@Output() messageEvent = new EventEmitter<string>();
sendMessage() {
this.messageEvent.emit(this.message);
//console.log(this.message);
}
////////////////////////////////////////////////// ///////////
app.component.ts(在導出類中...)
message = "";
receiveMessage($event){
this.message = $event;
//console.log($event);
}
////////////////////////////////////////////////// ///////////
header.component.html
<div class="hamburguer">
<a (click)="getUrl();">
<img src="assets/images/{{ message }}.png" id="hamburguer">
</a>
</div>
header.component.ts(在導出類中...)
@Input() message;
ngOnInit() {
if(window.location.pathname != "/settings"){
this.message = 'hamburguer';
}else{
this.message = 'cross';
}
}
發生這種情況是因為您只觸發一次事件。您需要刪除ngOninit函數並使用您自己的函數。 看看下面的StackBlitz示例
順便說一句,你寧願使用變量而不是使用URL.URL是動態的,可以改變,將變量傳遞給你的函數並根據它填充this.message
。
ngOnInit是第一次激活並調用一次的函數。 你應該在頁腳按鈕Home Button中添加另一個“if”語句,以便更改“message”變量。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.