我有一个下拉列表,我希望默认情况下有一个第一个空白元素,比如“选择一个选项”,当用户选择一个下拉元素时,第一个字段就会消失。稍后在setInterval的帮助下,我试图清理我的下拉列表,不选择任何选项,并从头开始查看下拉列表。我怎样才能实现它?这是我的代码。
//templates/home/home.component.html
<select [(ngModel)]='myselect' >
<option [value]="" selected >select and option</option>
<option *ngFor='let option of test' [value]="option.id">
{{option.nombre}}</option>
</select>
//components/home/home.component.ts
title = 'app';
myselect:any;
test:any= [{"id": "1", "nombre":"pedro" },{"id": "2",
"nombre":"yeison" }];
ngOnInit() {
this.timeoutFun();
}
timeoutFun() {
setTimeout(function(){
//clear my dropdown
this.myselect="";
}, 5000);
}
这是我的代码:
https://stackblitz.com/edit/angular-n8x7xo?file=src/app/templates/home/home.component.html
答案 0 :(得分:1)
如果我理解正确,我认为以下是你想要的。你需要一个*ngUf
选项消失,一些属性绑定它会触发它消失或重新出现。此外,在setTimeout中,由于您没有使用箭头函数,因此您正在丢失组件的范围,因此在更新这些值时,它们不会按预期应用于组件的实例。
//模板/家/ home.component.html
<h1>This is home component</h1>
<button (click)="open()">Open Modal</button>
<br>
<select (ngModel)='myselect' (change)="updateOptions()" >
<option *ngIf="foo" [value]="" selected >select and option</option>
<option *ngFor='let option of test' [value]="option.id">
{{option.nombre}}</option>
</select>
//组件/家/ home.component.ts
import { Component } from '@angular/core';
import { AppService } from '../../services/app.service';
import { ModalModel } from '../../models/modal.model';
declare let $: any;
@Component({
selector: 'home',
templateUrl: '../../templates/home/home.component.html',
providers: [AppService]
})
export class HomeComponent {
title = 'app';
foo = true;
modelData = new ModalModel();
constructor(
private _service: AppService
){}
myselect:any;
test:any= [{"id": "1", "nombre":"pedro" },{"id": "2", "nombre":"yeison" }];
ngOnInit() {
this.timeoutFun();
}
timeoutFun() {
setTimeout(() =>{
//clear my dropdown
this.myselect="";
this.foo = true;
alert('here');
}, 5000);
}
open()
{
this.modelData.header = 'This is my dynamic HEADER from Home component';
this.modelData.body = 'This is my dynamic BODY from Home component';
this.modelData.footer = 'This is my dynamic footer from Home component';
this._service.open(this.modelData);
}
updateOptions() {
this.foo = false;
}
}