我正在使用angular4和Redux以及角度材料来设计我的网页。 我正在尝试将md-select面板设置为打开。 示例场景:单击按钮调度操作以打开选择面板,打开以显示所有选项。
我正在使用redux操作来操纵我的组件状态。所以基本上我需要触发一个操作来将select设置为打开。
有什么建议吗?
答案 0 :(得分:3)
使用Material2示例作为此答案的起点。以下是如何做到这一点:
为您的面板提供ID,例如
mySelect
<md-select placeholder="Favorite food" #mySelect>
<md-option *ngFor="let food of foods" [value]="food.value">
{{ food.viewValue }}
</md-option>
</md-select>
...然后更改您的组件类:
import {Component, ViewChild, AfterViewInit } from '@angular/core';
import {MdSelect} from '@angular/material';
@Component({
selector: 'select-overview-example',
templateUrl: 'select-overview-example.html',
})
export class SelectOverviewExample implements AfterViewInit {
foods = [
{value: 'steak-0', viewValue: 'Steak'},
{value: 'pizza-1', viewValue: 'Pizza'},
{value: 'tacos-2', viewValue: 'Tacos'}
];
@ViewChild('mySelect') mySelect: MdSelect;
ngAfterViewInit(){
this.mySelect.open();
}
}
此处有Plunker链接:PLUNKER DEMO
答案 1 :(得分:1)
此示例显示如何订阅状态,以便下拉列表将是当前状态。因此,如果您希望它最初打开,请将initialState
更改为true。
有一个按钮可以调度切换状态操作以打开下拉列表。
可以修改此选项以切换或创建单独的打开/关闭按钮或任何您需要的按钮。
<强> state.ts 强>
export interface AppState {
isDropDownOpen: boolean
}
const initialState: AppState = {
isDropDownOpen: false;
};
export function appReducer(
state: AppState = initialState,
action: any
): AppState {
switch (action.type) {
case 'toggleSelect': {
state.isDropDownOpen = action.payload
return state;
}
default: {
return state;
}
}
}
我-component.ts 强>
import {Component, ViewChild, AfterViewInit } from '@angular/core';
import {MdSelect} from '@angular/material';
@Component({
selector: 'my-component',
template: `
<md-select placeholder="Favorite food" #mySelect>
<md-option *ngFor="let food of foods" [value]="food.value">
{{ food.viewValue }}
</md-option>
</md-select>
<button (click)="openSelect()"> Open Select </button>
`,
})
export class SelectOverviewExample implements AfterViewInit {
foods = [
{value: 'steak-0', viewValue: 'Steak'},
{value: 'pizza-1', viewValue: 'Pizza'},
{value: 'tacos-2', viewValue: 'Tacos'}
];
@ViewChild('mySelect') mySelect: MdSelect;
controller( private store: Store<AppState>){
store.select(state => state.isDropDownOpen).subscribe(isDropDownOpen => {
if(isDropDownOpen){
this.mySelect.open()
} else {
this.mySelect.close()
}
})
}
openSelect(){
this.store.dispatch({ type: toggleSelect, payload: true })
}
}
答案 2 :(得分:-2)