I am using template driven form and am trying to set the value of the form elements based on some object properties, however i face the following on doing so. Also here is my code for the TD form and how i am trying to access it.
.html file:
<div class="row">
<div class="col-xs-12">
<form (ngSubmit)="onAddDevice(f)" #f="ngForm">
<div class="row">
<div class="col-sm-5 form-group">
<label for="name">Name</label>
<input type="text" id="name" class="form-control" name="name" ngModel required>
</div>
<div class="col-sm-2 form-group">
<label for="type">Type</label>
<input type="text" id="type" class="form-control" name="type" ngModel required>
</div>
<div class="col-sm-5 form-group">
<label for="platform">Platform</label>
<input type="text" id="platform" class="form-control" name="platform" ngModel required>
</div>
<div class="col-sm-2 form-group">
<label for="udid">UDID</label>
<input type="text" id="udid" class="form-control" name="udid" ngModel required>
</div>
</div>
<div class="row">
<div class="col-xs-12">
<button class="btn btn-success" type="submit" [disabled]="!f.valid">Add</button>
<button class="btn btn-danger" type="button">Delete</button>
<button class="btn btn-primary" type="button">Clear</button>
</div>
</div>
</form>
</div>
</div>
.ts file:
@ViewChild('f') deviceForm: NgForm;
@Output() deviceAdded = new EventEmitter<DeviceModel>();
editedItemIndex: number;
editedDevice: DeviceModel;
constructor(private deviceService: DeviceService, private route: ActivatedRoute) { }
ngOnInit() {
this.route.params
.subscribe(
(params: Params) =>{
this.id = +params['id'];
this.editMode = params['id'] != null;
if ( this.editMode) {
this.editedItemIndex = params['id'];
this.editedDevice = this.deviceService.getDevice(params['id']);
console.log(this.editedDevice.frame);
this.deviceForm.setValue({
name: this.editedDevice.name,
platform: this.editedDevice.platform,
type: this.editedDevice.type,
udid: this.editedDevice.frame
});
}
}
);
}
The problem is because of calling the setValue method on the form.
As you are using template driven forms, the form controls will not be registered on init of the component. As the error message suggests use the setTimeout(), wrap your setvalue() as below, it will fix the issue.
setTimeout(() => {
this.deviceForm.setValue({
name: this.editedDevice.name,
platform: this.editedDevice.platform,
type: this.editedDevice.type,
udid: this.editedDevice.frame
});
}, );
Hope it helps...:)
I faced the same problem, and I solved it doing this (the code snippet below, uses your form controls):
this.deviceForm.form.patchValue({
name: this.editedDevice.name,
platform: this.editedDevice.platform,
type: this.editedDevice.type,
udid: this.editedDevice.frame
});
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With