Angular6 写一个简单的Select组件示例

前端之家收集整理的这篇文章主要介绍了Angular6 写一个简单的Select组件示例前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。

Select组件目录结构

(); label: string; @ContentChildren(NzOptionDirective,{ descendants: true }) options: QueryList;

ngAfterContentInit() {
this.options.forEach(option => {
option.select.subscribe(() => {
this.value = option.value;
this.label = option.renderLabel();
this.options.map(r => r.isSelected = false);
option.isSelected = true;
this.valueChange.emit(option.value);
})
setTimeout(() => {
option.isSelected = option.value === this.value;
if (option.isSelected) {
this.label = option.renderLabel();
this.valueChange.emit(option.value);
}
});
})
}

@HostListener('click')
onClick() {
this.isOpen = !this.isOpen;
}
}

:host .current{
padding:5px 10px;
background:red;
color:#FFF;
text-align: center;
width:40px;
outline: none;
border: none;
}

::ng-deep div:not(.current):hover{
background:green;
color:#FFF;
}

::ng-deep .selected {
font-weight: 700;
background: red;
color:#FFF;
}

@Directive({
selector:'[nzOption]'
})
export class NzOptionDirective{
@Input() value:string;
constructor(private el:ElementRef){}
@Output() select = new EventEmitter();

@HostBinding("class.selected")
isSelected: boolean;

renderLabel(){
return (this.el.nativeElement.textContent || "").trim();
}

@HostListener('click')
onClick(){
this.select.emit();
}

}

应用 Select 组件

结构

@Component({
selector: 'my-app',templateUrl: './app.component.html',styleUrls: ['./app.component.css']
})
export class AppComponent {
name = 'Angular';

defaultValue: any = 'value5'

menus: any[] = [];

ngOnInit() {
for (let i = 0; i <= 6; i++) {
this.menus.push({
value: 'value' + i,label: 'item' + i
})
}
}
}

 select value is {{defaultValue|json}}

以上就是本文的全部内容,希望对大家的学习有所帮助,也希望大家多多支持编程之家。

猜你在找的JavaScript相关文章