Angular6:基于下拉菜单中的选定值打开对话框

时间:2018-11-07 10:35:25

标签: angular select dialog dropdown

我有一个p-dropdown,列表中包含多个选择[options]="newUnitSelectItems"的选项。目标是:如果用户从该选项列表中选择“其他”,则应打开一个新对话框。如果用户从列表中选择任何其他值,则应执行简单的console.log。我该如何实现?

new.component.html
      <p-dropdown name="newUnit" id="newUnit" [options]="newUnitSelectItems"
                  [(ngModel)]="Id"
                  (onChange)="performConsoleLog(Id, 'calc')"
                  ></p-dropdown>


new.component.ts
  performConsoleLog(unit: string, parameter: string) {
    if (parameter === 'calc') {
     console.log("No dialog open, unit: " + unit);
    }
  }

  newUnitSelectItems() {
    let selectItems: SelectItem[] = [
      {label: "%", value:"%"},
      {label: "g", value:"g"},
      {label: "other", value:"other"}
    ];
    return selectItems;
  }

我想这里的(onChange)是错误的,因为每次单击都会调用performConsoleLog()。有没有办法检查从html中的[options]="newUnitSelectItems"中选择哪个值?

非常感谢!

2 个答案:

答案 0 :(得分:1)

  

您可以在command的选项中使用p-dropdown

 newUnitSelectItems() {
    let selectItems: SelectItem[] = [
      {label: "%", value:"%"},
      {label: "g", value:"g"},
      {label: "other", value:"other", command :()=> this.openModal()} //<--command is here
    ];

   openModal(){
     console.log("Opening modal ");
   }

从选择框中删除onChange

答案 1 :(得分:1)

您可以使用$event事件中的change来获取所选的值:

<p-dropdown name="newUnit" id="newUnit" [options]="newUnitSelectItems"
                  [(ngModel)]="Id"
                  (onChange)="performConsoleLog($event)"
                  ></p-dropdown>

在您的TS中:

performConsoleLog($event) {
    if ($event.value.label === 'other') {
     // open your dialog.
    }
}

此致