我经常需要添加setTimeout才能使指令与Ionic正确运行。
我的配置:
Ionic:
ionic (Ionic CLI) : 4.0.1 (/Users/rguerin/.nvm/versions/node/v6.10.1/lib/node_modules/ionic)
Ionic Framework : ionic-angular 3.1.1
@ionic/app-scripts : 1.3.7
System:
NodeJS : v6.10.1 (/Users/rguerin/.nvm/versions/node/v6.10.1/bin/node)
npm : 3.10.10
OS : macOS High Sierra
我的模板:
<ion-list [formGroup]="formGroup">
<ion-item *ngIf="countries">
<ion-label floating>
{{ 'customer.country' | translate }}
<span class="required" ion-text color="red">*</span>
</ion-label>
<ion-select formControlName="Country">
<ion-option *ngFor="let c of countries" [value]="c.In">{{c.Out}}</ion-option>
</ion-select>
</ion-item>
例如,如果我尝试设置这样的表单控件值,那么在没有setTimeout的情况下它将无法正常工作:
private setFormControlValue(propertyName: string, value: string, stockEmpty?: boolean): void {
let formControl: AbstractControl = this.formGroup.controls[propertyName];
if (_.isEmpty(value) && !stockEmpty) {
return;
} else {
if (!_.isEmpty(formControl) && !_.isNil(formControl)) {
this.logger.trace('Setting value %s for control : ', value, formControl);
setTimeout(() => formControl.setValue(value), 100);
}
}
}
当我想调整内容大小时也会发生:
ngOnInit(): void {
setTimeout(() => this.content.resize(), 100);
}
它有时甚至可以在超时时间为“ 0”毫秒的情况下工作。我想避免在所有地方都使用超时,但给人的印象是Ionic需要在不同的“线程”中运行指令以正确执行。
如果有人遇到相同的问题或知道更好的解决方法,我很乐意接受。
答案 0 :(得分:1)
您尝试过吗:
this.formGroup.get('Country').setValue('toto');
立即为我工作
答案 1 :(得分:1)
以我的经验,setTimeout
有时可以解决DOM操作和DeviceReady函数的问题。
我觉得这主要是由于 Angular 的消化环性能。
这里的stackoverflow有点旧了post,而且写得很好。
感谢阅读我的糟糕答案。