简体   繁体   中英

Angular 8 - Clicked button only does function() once

A button is only doing the function once, the video shows the problem: https://vimeo.com/342491616

The logic goes like this: When 'home' (inside footer.component) is clicked, sends function to parent(app.component), and then this one sends it to 'hamburguer' button (inside header.component).

I've read it may be something related to ngOnChanges but I tried it several times with it and it didn't work, but maybe I was using it wrong(?)

Code here:

footer.component.html

<a (click)="sendMessage()" routerLink="/page"><img src="assets/images/homebutton.png" class="footer_buttons" id="home_button"></a>

footer.component.ts (inside export class...)

message: string = "hamburguer";

@Output() messageEvent = new EventEmitter<string>();

sendMessage() {
    this.messageEvent.emit(this.message);
    //console.log(this.message);
}

/////////////////////////////////////////////////////////////

app.component.ts (inside export class...)

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 (inside export class...)

@Input() message;

ngOnInit() {
  if(window.location.pathname != "/settings"){
    this.message = 'hamburguer';
  }else{
    this.message = 'cross';
  }
}

This is happening because you fire the event only once.You need to remove the ngOninit Function and use your own function instead. Take a look at the following StackBlitz example

By the way,You rather work with variables instead working with the URL.URL is dynamic and could change, Pass a variable into your function and populate this.message according to that.

ngOnInit is a function that active on the first time, and invoked once. you should add another "if" statement in the footer button, Home Button, in order to change the "message" variable.

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.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM