【发布时间】:2017-01-18 10:17:57
【问题描述】:
我有一个函数需要在我的组件中设置this.value 后运行。我尝试使用生命周期挂钩ngAfterContentInit(),但此时this.value 要么为空,要么为空字符串。
我正在引用我的组件,例如:
<add-select name="address" [options]="knownAddresses" [(ngModel)]="user.address"></add-select>
我的组件看起来像
const CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR: any = {
provide: NG_VALUE_ACCESSOR,
useExisting: forwardRef(() => AddSelect),
multi: true
};
@Component({
selector: 'add-select',
templateUrl: 'build/components/add-select/add-select.html',
providers: [CUSTOM_INPUT_CONTROL_VALUE_ACCESSOR]
})
export class AddSelect implements ControlValueAccessor {
@Input() options: any[];
// * NEED THIS TO RUN AFTER this.value IS CURRENT WHICH IS PASSED IN VIA ngModel
private syncModelAndOptions() {
if (this.options && this.value) {
const modelOption = _.find(this.options, option => {
return item == this.value || (option._id && this.value._id && option._id === this.value._id);
});
if (modelOption) {
this.value = modelOption;
} else {
this.options.push(this.value);
}
}
}
//get accessor
get value(): any {
...
};
//set accessor including call the onchange callback
set value(v: any) {
...
}
//From ControlValueAccessor interface
writeValue(value: any) {
...
}
//From ControlValueAccessor interface
registerOnChange(fn: any) {
...
}
//From ControlValueAccessor interface
registerOnTouched(fn: any) {
...
}
【问题讨论】:
标签: angular typescript ionic2