如何在Angular中显示/隐藏按钮

4
我希望在按钮状态为“approve”时显示“不批准”按钮,在“pending”状态下显示“批准”按钮。我已经正确传递了值,但两个按钮总是同时显示。
这是我的.ts文件:
    export class NotificationComponent implements OnInit {

      notices: notification[] = [];
      public approve_show: boolean = false;
      public disapprove_show: boolean = false;

      constructor(
        private http: HttpClient,
        private router: Router,
      ) { }

      ngOnInit() {

    var url = "http://localhost:3000/notification/view";

    this.http.get<any>(url).subscribe(res => {
      this.notices = res;
      var i = 0;

      for (var prop in res) {
        if (res.hasOwnProperty(prop)) {
          // console.log(res[i].state)          
          if (res[i].state == 'Approved') {
            console.log("approved")
            this.disapprove_show = true
          }
          else {
            this.approve_show = true
          }
          i++;
        }
      }

    }, (err) => {
      console.log(err);
    });
  }
}

这是我的HTML代码。
<button *ngIf="approve_show" mat-raised-button class="approve_btn">Approve</button>
<button *ngIf="disapprove_show"  mat-raised-button color="warn" style="width:100px;">Disapprove</button>

调试你的代码。你循环多次并在循环的不同迭代中执行if/else的两个部分。使用断点查看实际发生的情况。 - Igor
1
你不需要两个变量。你可以在条件中使用 ! - Sagar V
GET调用返回的对象是什么?对于响应对象的某些属性,approve_show设置为true,而对于其他属性,则设置为disapprove_show为true。 - Nithin Kumar Biliya
3个回答

3

嘿,你的代码没问题。

你需要修复这个问题,在 this.disapprove_show = true 后添加 this.approve_show = false,并在 this.approve_show = true 后添加 this.disapprove_show = false

问题在于两个变量同时为真。


2

由于您正在使用此列表,因此请使用以下内容。

<button *ngIf="res.state=='Approved'" mat-raised-button color="warn" style="width:100px;">

问题在于您正在为按钮使用全局变量。


1
    if (res[i].state == 'Approved') { 
console.log("approved") 
this.disapprove_show = true 
this.approve_show = false
} else {
this.approve_show = true 
this.disapprove_show = false
}

根据要求,似乎每次只会显示一个按钮...请告诉我如果我理解错了...

我也使用了这段代码。但是它没有起作用。无论如何,谢谢。 - Sachin Muthumala

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接