问题
<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