简体   繁体   中英

Why doesn't ngOnInit varible change affect the html in angular 2/4?

i have user object that i am subscribing to. If the user is equal to a certain name, than it shouldn't show a button. I don't know why it doesn't affect the ngIf in html.

My Html

 <input *ngIf = "showDelete" type = "button" (click) = 
 "deleteCustomer(customer._id)" value = "Delete" class = "btn btn-danger">

My ngOnInit in appcomponent.ts

    ngOnInit() {

let showDelete:boolean =true;

this.authService.getProfile().subscribe(profile => {
  this.username = profile.user.name

  if (this.username=="admin"){

    showDelete=false;
  }
},

If i console.log the this.username and show delete i get the expected values, but it is not changing the logic in html

You should declare the showDelete variable as part of your component so that it is accessible from the template:

public showDelete: boolean = true;

ngOnInit(): void {
    this.authService.getProfile().subscribe(profile => {
        this.username = profile.user.name;
        if (this.username == "admin") {
            this.showDelete = false;
        }
    });
}

You have no access to showDelete from the template, because it is defined within ngOnInit()

Try to define it like this:

 class MyClass {
   showDelete:boolean;

   ngOnInit() {
    this.authService.getProfile().subscribe(profile => {
      this.username = profile.user.name
      if (this.username=="admin"){
        this.showDelete = false;
      }
    }
}

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