我使用来自Angular Material的简单下拉菜单来触发选择时的事件/功能(本例为api调用)。我几乎尝试了所有事情,看到了很多帖子,但仍然想念一些东西
HTML:
<mat-form-field>
<mat-label>Choose a camera</mat-label>
<mat-select [(ngModel)]="selected" (ngModelChange)="test()">
<mat-option *ngFor="let c of cameras" [value]="c.name">
{{c.name}}
</mat-option>
</mat-select>
</mat-form-field>
ts:
export class MoviesComponent implements OnInit {
selected:string;
test() {
console.log(this.selected);
}
}
这很简单,是很多方法之一,但是没有任何效果!有什么想法吗?
答案 0 :(得分:1)
您有2个选项。模型形式或反应形式。
控制器
export class MoviesComponent implements OnInit {
selected:string;
test() {
// API call here
console.log(this.selected)
}
}
模板
<mat-form-field>
<mat-label>Choose a camera</mat-label>
<mat-select [(value)]="selected" (selectionChange)="test()">
<!-- OR <mat-select [(ngModel)]="selected" (ngModelChange)="test()"> -->
<mat-option *ngFor="let c of cameras" [value]="c.name">
{{c.name}}
</mat-option>
</mat-select>
</mat-form-field>
控制器
export class MoviesComponent implements OnInit, OnDestroy {
completed$ = new Subject<any>();
selected: string;
selectedControl = new FormControl(this.selected);
ngOnInit() {
this.selectedControl.valueChanges.pipe(
takeUntil(this.completed$),
switchMap(selected => {
console.log(selected);
// return API call here
})
).subscribe(
response => {
// handle respone from API
},
error => {
// handle error from API
}
);
}
ngOnDestroy() {
this.completed$.next();
this.completed$.complete();
}
}
模板
<mat-form-field>
<mat-label>Choose a camera</mat-label>
<mat-select [formControl]="selectedControl">
<mat-option *ngFor="let c of cameras" [value]="c.name">
{{c.name}}
</mat-option>
</mat-select>
</mat-form-field>