Angular2 bool范围问题

时间:2017-07-06 09:29:51

标签: angular toggle dropdown

我尝试使用angular-cli v1.0.0和angular 2.4.10在Angular2中进行基本选择,但问题是isOpen变量在选择选项时没有切换,因此关闭菜单。

BasicSelect.ts
@Component({
  selector: 'basic-select',
  templateUrl: './basic-select.component.html',
  styleUrls: ['./basic-select.component.less']
})
export class BasicSelect implements OnInit, OnDestroy {
  // Input is populated from an outside component after an http call
  @Input()
  selectOptions:Array<any>;
  // 
  @Input()
  selectedOption:BehaviorSubject<any>;

  public isOpen:boolean;

  public constructor() {
    this.isOpen = false;
  }
  //THIS WORKS
  public toggleDropdown():void {
    this.isOpen = !this.isOpen;
  }
  //THIS DOESN'T WORK
  public selectOption(opt):void {
    this.isOpen = false;
    this.selectedOption.next(opt);
  }
}


BasicSelect.html
<div class="dropdown_container" (click)="toggleDropdown()" [ngClass]="{ 'show': isOpen }">
  <dl>
    <dt><span>{{selection}}</span></dt>
  </dl>
  <ul class="dropdown_items">
    <li *ngFor="let option of selectOptions" (click)="selectOption(option)">
      <span>{{option}}</span>
    </li>
  </ul>
</div>

问题在于,如果我单击下拉容器,就像魅力一样,但在实际选择选项时,组件看不到isOpen更改。

1 个答案:

答案 0 :(得分:1)

这样做:

public selectOption(event, opt):void {
    event.stopPropagation()
    this.isOpen = false;
    this.selectedOption.next(opt);
  }

这是因为,当您单击li元素时,您将触发两个单击功能。一个在li,第二个在外div。因此,event.stopPropagation()将停止点击事件的传播。只触发一次点击。

更多地了解here

希望它有所帮助。 : - )

相关问题