【发布时间】:2019-03-16 09:13:12
【问题描述】:
我经常需要添加一个 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 需要在不同的“线程”中运行指令才能以正确的方式执行。
如果有人遇到同样的问题或知道更好的解决方法,我很乐意接受。
【问题讨论】:
-
你在哪个活动做这个?
-
这在 ngOnInit() 方法中,但我的代码中几乎到处都有这个问题
-
不在 ngOnInit() 内部,它由用户操作触发(单击选定的组件)。我没有显示其余代码,因为此方法的行为不应该受到它的影响。
-
你能看看this answer吗?
-
也很有意思,谢谢分享!
标签: angular typescript ionic-framework ionic3