代码之家  ›  专栏  ›  技术社区  ›  prabhat gundepalli

优化angular代码以获得更好的可扩展性和良好的体系结构

  •  0
  • prabhat gundepalli  · 技术社区  · 7 年前

    我有下面的html代码。(我不打算使用*ngFor)

       <div *ngIf = 'showTemplate1'>Template 1</div>
       <div *ngIf = 'showTemplate2'>Template 2</div>
       <div *ngIf = 'showTemplate3'>Template 3</div>
       <div *ngIf = 'showTemplate4'>Template 4</div>
       <div *ngIf = 'showTemplate5'>Template 5</div>
       <div *ngIf = 'showTemplate6'>Template 6</div>
       <div *ngIf = 'showTemplate7'>Template 7</div>
       <div *ngIf = 'showTemplate8'>Template 8</div>
    

    在我的TS文件中,我有如下内容

    displayTemplates(){
       if( condition1 ){
        this.showTemplate1 = true;
        this.showTemplate2 = true;
        this.showTemplate3 = true;
        this.showTemplate4 = true;
        this.showTemplate5 = true;
        this.showTemplate6 = true;
        this.showTemplate7 = false;
        this.showTemplate8 = false;
       }
       else if( condition2 ){
        this.showTemplate1 = false;
        this.showTemplate2 = true;
        this.showTemplate3 = true;
        this.showTemplate4 = true;
        this.showTemplate5 = true;
        this.showTemplate6 = true;
        this.showTemplate7 = false;
        this.showTemplate8 = true;
       }
      else if( condition3 ){
        this.showTemplate1 = true;
        this.showTemplate2 = true;
        this.showTemplate3 = true;
        this.showTemplate4 = true;
        this.showTemplate5 = true;
        this.showTemplate6 = true;
        this.showTemplate7 = true;
        this.showTemplate8 = false;
       }
     }
    

    正如你在代码中看到的,它看起来像一个糟糕的代码。 有没有其他方法可以让它更干净、更安全 可伸缩 .

    1 回复  |  直到 7 年前
        1
  •  1
  •   Sunil Singh    7 年前

    下面是您可以在代码中进行的一些改进

    resetToTrue(){
        this.showTemplate1 = true;
        this.showTemplate2 = true;
        this.showTemplate3 = true;
        this.showTemplate4 = true;
        this.showTemplate5 = true;
        this.showTemplate6 = true;
        this.showTemplate7 = true;
        this.showTemplate8 = true;
    }
    
    displayTemplates(){
       if(condition1 ){
        this.resetToTrue();
        this.showTemplate7 = false;
        this.showTemplate8 = false;
       }
       else if( condition2 ){
        this.resetToTrue();
        this.showTemplate1 = false;
        this.showTemplate7 = false;
       }
      else if( condition3 ){
        this.resetToTrue();
        this.showTemplate8 = false;
       }
     }
    

    使用者 this.resetToTrue() 如果大多数字段为true,则可以创建一个方法 this.resetToFalse() 将所有值设置为 false .