以角度2

时间:2017-09-04 16:07:24

标签: angular

我想在选中复选框时动态添加和删除组件。我可以添加组件并在单击关闭按钮时将其删除。但是,如果我尝试从复选框中更改组件选择,则先前选择的组件仍然存在,它不会被删除。

以下是Demo

的工作演示
  

app.component.ts

  import { Component,ViewChild,ViewContainerRef ,ComponentFactoryResolver , AfterContentInit,OnInit,ComponentRef} from '@angular/core';
import { BoxOneComponent } from './boxOne.component';
import { BoxTwoComponent } from './boxTwo.component';
import { BoxThreeComponent } from './boxThree.component';
import { BoxFourComponent } from './boxFour.component';
import { SharedService } from './shared.service';

@Component({
  selector: 'my-app',
  templateUrl: './app.component.html',
  styleUrls: [ './app.component.css' ]
})
export class AppComponent {

  @ViewChild('parent',{read:ViewContainerRef}) parent;
  @ViewChild('widget') widget ;
  public resolve;
  public totalBoxLength:number = 0;

  constructor(private cfr:ComponentFactoryResolver,private sharedService : SharedService){

  }


  passedValue(data){
    data.forEach(element => {
      this.addWidget(element.name,element.length)
    });
  }

  addWidget(val,boxLength){
    this.totalBoxLength += boxLength;
    if(this.totalBoxLength<=8){
        let data;
        switch(val){
          case "BoxOneComponent":
            data = BoxOneComponent;
            break;
          case "BoxTwoComponent":
            data = BoxTwoComponent;
            break;
          case "BoxThreeComponent":
            data = BoxThreeComponent;
            break;
          case "BoxFourComponent":
            data = BoxFourComponent;
            break;
          case "BoxFiveComponent":
            data = BoxFiveComponent;
            break;
          case "BoxSixComponent":
            data = BoxSixComponent;
            break;
          case "BoxSevenComponent":
            data = BoxSevenComponent;
            break;
          case "BoxEightComponent":
            data = BoxEightComponent;
            break;
          case "BoxNineComponent":
            data = BoxNineComponent;
            break;
        }
        this.resolve = this.cfr.resolveComponentFactory(data);
        let cmp: ComponentRef<any> = this.parent.createComponent(this.resolve);
        cmp.instance.boxLength$.subscribe((value)=>this.totalBoxLength -= value)
        cmp.instance.close$.take(1).subscribe(() => cmp.destroy());
    }else{
        this.totalBoxLength -= boxLength;
    }

  }


}
  

BoxOne.component.ts

    import { Component, Input } from '@angular/core';
import { Subject } from 'rxjs';
import { SharedService } from './shared.service';

@Component({
  selector: 'box-one',
  template: `
    <div>
      <button (click)="close({'name':'BoxOneComponent','length':2})">Close</button>
    </div>
  `,
  styles: [`
    div{
      height:100px;
      width:40%;
      background-color:yellow;
      display:inline-block;
      margin:5px;
    }
    button{
      margin-left:48px;
    }
  `]
})
export class BoxOneComponent  {

  constructor(private sharedServ : SharedService){}

  public close$ = new Subject<void>();
  public boxLength$ = new Subject<number>();

  close(comps){
    this.sharedServ.sendComponentName(comps);
    this.close$.next(null);
    this.boxLength$.next(2);
  }

}

还有另外3个盒子组件。

  

widgetlist.html

<div class="modal fade" bsModal #widgetList="bs-modal" [config]="{backdrop: 'static'}" tabindex="-1" role="dialog" aria-labelledby="mySmallModalLabel" aria-hidden="true">
    <div class="modal-dialog modal-sm widget-width">
        <div class="modal-content widget-content">
            <div class="modal-header widget-header">
                <div class="modal-title">
                    <span class="widget-heading">List of all available widgets</span>
                    <span (click)="hideWidgetList()" class="close-span">Close</span>
                </div>
            </div>
            <div class="modal-body widget-body">
                <div><input type="checkbox" #BoxOneComponent name="Box One" (click)="selectWidget({'name':'BoxOneComponent','length':2})"> Box One </div>
                <div><input type="checkbox" #BoxTwoComponent name="Box Two" (click)="selectWidget({'name':'BoxTwoComponent','length':1})"> Box Two </div>
                <div><input type="checkbox" #BoxThreeComponent name="Box Three" (click)="selectWidget({'name':'BoxThreeComponent','length':1})"> Box Three </div>
                <div><input type="checkbox" #BoxFourComponent name="Box Four" (click)="selectWidget({'name':'BoxFourComponent','length':2})"> Box Four </div>
            </div>
            <div class="modal-footer widget-footer ">
                <button class="cancel-button" (click)="hideWidgetList()">Cancel</button>
                <button class="update-button " (click)="updateWidgetList();hideWidgetList()">Update</button>
            </div>
        </div>
    </div>
</div>
  

widgetlist.ts

import { Component,ViewChild ,ElementRef , ViewRef , Output , EventEmitter} from '@angular/core';
import { ModalDirective } from 'ngx-bootstrap';
import { SharedService } from './shared.service';

@Component({
  selector: 'app-widget-list',
  templateUrl: './widget-list.component.html',
  styles: [
`
    .close-span{
    cursor: pointer;
    float: right;
    border: 1px solid black;
  }

.widget-body div{
  display:inline-block;
  width:45%;
}

`
  ]
})
export class WidgetList  {

  @ViewChild('widgetList') widgetList : ModalDirective ;
  @ViewChild('BoxOneComponent') boxOne;
  @ViewChild('BoxTwoComponent') boxTwo;
  @ViewChild('BoxThreeComponent') boxThree;
  @ViewChild('BoxFourComponent') boxFour;
  @Output() selected = new EventEmitter();
  constructor( private elemRef : ElementRef,private sharedService:SharedService) { 
    this.sharedService.shareComponentName$.subscribe(val=>{
      this.selectWidget(val);
      this.triggerChecked(val);
    });
  }
  public widgetSelected : Array<string> =[];
  public widgetSelectedName : Array<string> = [];
  public widgetAlreadyInList : Array<any>;

  showWidgetList():void{
    this.widgetList.show();
  }

  hideWidgetList():void{
    this.widgetList.hide();
  }

public pushedArray =[];
  selectWidget(widget){
    let indexOfSelectedWidget = this.widgetSelectedName.indexOf(widget.name);
      if(indexOfSelectedWidget === -1){
          this.widgetSelected.push(widget);
          this.widgetSelectedName.push(widget['name']);
      }else{
          this.widgetSelected.splice(indexOfSelectedWidget,1);
          this.widgetSelectedName.splice(indexOfSelectedWidget,1);
      }      
  }

  updateWidgetList(){
      console.log(this.widgetSelected);
      sessionStorage.setItem("existingWidgets",JSON.stringify(this.widgetSelected))
      this.selected.emit(this.widgetSelected);
  }

  triggerChecked(component){

    switch(component.name){
      case "BoxOneComponent":
        this.boxOne.nativeElement.checked = false;
        break;
      case "BoxTwoComponent":
        this.boxTwo.nativeElement.checked = false;
        break;
      case "BoxThreeComponent":
        this.boxThree.nativeElement.checked = false;
        break;
      case "BoxFourComponent":
        this.boxFour.nativeElement.checked = false;
        break;
    }

  }

}

0 个答案:

没有答案