I've been trying to create a simple directive in Angular 5 but hit walls. I recently discovered that adding my code inside a setTimeout
function makes it work as I expect. In this case I expect the form to appear populated with "yolo
"
I don't completely understand why. I understand that it has to do with the way Angular bootstraps but I don't understand why it is that way - and especially why code in the constructor is discarded (After all, then what's the point of the constructor?)
Please find a simplified copy of the code in question below:
@Directive({
selector: '[formControlName][phone]',
host: {
'(ngModelChange)': 'onInputChange($event)'
}
})
export class PhoneMask {
constructor(public model: NgControl) {
// with setTimeout
setTimeout(() => {
this.model.valueAccessor.writeValue('yolo');
});
// without setTimeout
// this.model.valueAccessor.writeValue('yolo');
}
}
@Component({
selector: 'my-app',
providers: [],
template: `
<form [formGroup]="form">
<input type="text" phone formControlName="phone">
</form>
`,
directives: [PhoneMask]
})
export class App {
constructor(fb:FormBuilder) {
this.form=fb.group({
phone:['']
})
}
}
@NgModule({
imports: [ BrowserModule, FormsModule, ReactiveFormsModule ],
declarations: [ App, PhoneMask ],
bootstrap: [ App ]
})
export class AppModule {}