【问题标题】:Why doesn't ngOnInit varible change affect the html in angular 2/4?为什么 ngOnInit 变量更改不会影响角度 2/4 中的 html?
【发布时间】:2017-05-24 20:45:18
【问题描述】:

我有我正在订阅的用户对象。如果用户等于某个名称,则不应显示按钮。我不知道为什么它不会影响 html 中的 ngIf。

我的 HTML

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

我在 appcomponent.ts 中的 ngOnInit

    ngOnInit() {

let showDelete:boolean =true;

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

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

    showDelete=false;
  }
},

如果我 console.log this.username 并显示删除我得到预期的值,但它不会改变 html 中的逻辑

【问题讨论】:

  • 只需将showDelete 变量移到您的ngOnInit() 函数之外的组件即可

标签: javascript html angular typescript


【解决方案1】:

您应该将showDelete 变量声明为组件的一部分,以便可以从模板访问它:

public showDelete: boolean = true;

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

【讨论】:

    【解决方案2】:

    您无法从模板访问 showDelete,因为它是在 ngOnInit() 中定义的

    尝试这样定义:

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

    【讨论】:

      猜你喜欢
      • 2018-10-26
      • 2019-08-09
      • 2020-09-15
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多