How to prevent Dialog opening twice in angular material using angular5

北战南征 提交于 2020-01-30 06:33:12

问题


    <mat-autocomplete #auto="matAutocomplete">
 <mat-option *ngFor="let person of filteredPersons | async" [value]="person.name" (onSelectionChange)="selectedPersonsInDialog(person)"> <img style="vertical-align:middle;" aria-hidden src="{{person.imgUrl}}" width="30" height="30" /> <span>{{ person.name }}</span> | <small>ID: {{person.id}}</small> </mat-option> </mat-autocomplete>
        <mat-autocomplete #auto="matAutocomplete">
          <mat-option *ngFor="let person of filteredPersons |  async" [value]="person.name"(onSelectionChange)="selectedPersonsInDialog(person)">
          {{person}}  
          </mat-option>  
        </mat-autocomplete>

This is my method in the component class:- Actually selectedPersonsInDialog function is being called twice so, always it displays 2 times dialog with latest selected and one previous selected value.

I want to display a dialog only once with latest value selected.

selectedPersonsInDialog(person){
 this.selectedPerson=person;
alert(this.selectedPerson); 
 let dialogRef = this.dialog.open(AddListOfPersonDialog, {
      width: '500px',
      data: { person:this.selectedPerson}
    });
  }*

回答1:


when selection change event pass in every option, so got more then one event. but you got $event.source.selected is true in one event which is you selected. so you can manage it.

your html should be like

<mat-autocomplete #auto="matAutocomplete">
                <mat-option *ngFor="let person of filteredPersons | async" [value]="person.name"
                            (onSelectionChange)="selectedPersonsInDialog($event.source.selected,person)">
                    <img style="vertical-align:middle;" aria-hidden  src="{{person.imgUrl}}" width="30" height="30"/>
                    <span>{{ person.name }}</span>
                    <small>ID: {{person.id}}</small>
                </mat-option>
            </mat-autocomplete>
            <mat-autocomplete #auto="matAutocomplete">
            <mat-option *ngFor="let person of filteredPersons |  async" [value]="person.name"
                        (onSelectionChange)="selectedPersonsInDialog($event.source.selected,person)">
                {{person}}
             </mat-option>
        </mat-autocomplete>

your component function should be like

selectedPersonsInDialog(isSelected: boolean,person){
if(isSelected){
   this.selectedPerson=person;
   alert(this.selectedPerson); 
   let dialogRef = this.dialog.open(AddListOfPersonDialog, {
      width: '500px',
      data: { person:this.selectedPerson}
    });
  }
}


来源:https://stackoverflow.com/questions/48183184/how-to-prevent-dialog-opening-twice-in-angular-material-using-angular5

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!