角绑定ng-if

时间:2018-10-24 18:27:52

标签: javascript angular

我无法正确绑定,应该在点击时切换。 ng-reflect-ng-if如果变为true并保持为true,则再次单击它应该为false,我也尝试过(clickoutside)但没有运气。从stackoverflow也跟随了这个问题 Binding a boolean value using *ngIf

<!--bindings={
      "ng-reflect-ng-if": "true"}-->

TS代码

 showAdditionalGraceInfo: boolean = false;
showAdditionalGraceInfo: boolean = false;

       toggleAdditionalGraceInfo() {

        this.showAdditionalGraceInfo = !this.showAdditionalGraceInfo;
        if(this.showAdditionalGraceInfo === true){
          this.showAdditionalGraceInfoWrapper = true;
       } else{
         this.showAdditionalGraceInfoWrapper = false
       }
      }

HTML代码

 <span (click)="toggleAdditionalGraceInfo()">
                        <span *ngIf="showAdditionalGraceInfoWrapper">
                            {{graceDaysAdditionalInfo}}
                        </span>
                    </span>

2 个答案:

答案 0 :(得分:0)

尝试一下

代码TS

toggleAdditionalGraceInfo() {
    if(!this.showAdditionalGraceInfo){
      this.showAdditionalGraceInfoWrapper = true;
   } else{
     this.showAdditionalGraceInfoWrapper = false
   }
}

代码HTML

<span (click)="toggleAdditionalGraceInfo()">
   <ng-container *ngIf="showAdditionalGraceInfoWrapper">
     <span>{{graceDaysAdditionalInfo}}</span>
   </ng-container>
</span>

答案 1 :(得分:0)

您可能不需要两个变量来进行操作。如果必须同时使用这两个变量,则可以采用这种方法。

<span id="test" (click)="showAdditionalGraceInfoWrapper = showAdditonalGraceInfo = 
  !showAdditionalGraceInfoWrapper">
        <span *ngIf="showAdditionalGraceInfoWrapper">
          {{graceDaysAdditionalInfo}}
      </span>
</span>

  showAdditionalGraceInfoWrapper:boolean = true;
  showAdditonalGraceInfo:boolean = true;
  graceDaysAdditionalInfo: string = "test"

示例:https://stackblitz.com/edit/angular-vlfmur