Reputation: 242
I'm new to Angular, I'm trying to set a value to an input using typescript to an HTML input, it is working fine however, when I submit the form it reads the value as an empty string, if I typed anything in the input in addition to the value that has been set the from submits with the value successfully, but doesn't submit if the value is set without changing anything manually, please advise if there is a better approach or how to correct this, thanks in advance.
company.component.html
<input type="text" id="LogoImageUrl" formControlName="LogoImageUrl">
company.component.ts
this.editCompanyForm = this.fb.group({
LogoImageUrl: new FormControl({ value: ''})
})
this.image = (
<HTMLInputElement>document.getElementById("LogoImageUrl")
).value = this.imageUrl
uploadFile(file) {
const contentType = file.type;
const bucket = new S3(
{
accessKeyId: 'key',
secretAccessKey: 'key',
region: 'region'
}
);
const params = {
Bucket: 'name',
Key: 'url' + file.name,
Body: file,
ACL: 'public-read',
ContentType: contentType
};
bucket.upload(params, function (err, data) {
if (err) {
console.log('There was an error uploading your file: ', err);
return false;
}
console.log('Successfully uploaded file.', data);
return true;
});
bucket.upload(params).on('httpUploadProgress', function (evt) {
console.log(evt.loaded + ' of ' + evt.total + ' Bytes');
}).send(function (err, data) {
if (err) {
console.log('There was an error uploading your file: ', err);
return false;
}
this.imageUrl = data.Location;
this.editCompanyForm.patchValue({
'LogoImageUrl': this.imageUrl
});
return true;
});
}
Upvotes: 0
Views: 1512
Reputation: 27303
You have to use arrow function for s3 instance to bind current component this context.
Try this:
component.ts
uploadFile(file) {
const contentType = file.type;
const bucket = new S3(
{
accessKeyId: 'key',
secretAccessKey: 'key',
region: 'region'
}
);
const params = {
Bucket: 'name',
Key: 'url' + file.name,
Body: file,
ACL: 'public-read',
ContentType: contentType
};
bucket.upload(params,(err, data)=> {
if (err) {
console.log('There was an error uploading your file: ', err);
return false;
}
console.log('Successfully uploaded file.', data);
return true;
});
bucket.upload(params).on('httpUploadProgress', (evt)=>{
console.log(evt.loaded + ' of ' + evt.total + ' Bytes');
}).send(()=> (err, data) {
if (err) {
console.log('There was an error uploading your file: ', err);
return false;
}
this.imageUrl = data.Location;
this.editCompanyForm.patchValue({
'LogoImageUrl': this.imageUrl
});
return true;
});
}
Upvotes: 1
Reputation: 109
Have you initialized the formbuilder in the ngOnInit ()? If you have not done so, it will give you undefined.
Upvotes: 0
Reputation: 650
You can try
this.editCompanyForm.controls["LogoImageUrl"].setValue(this.imageUrl);
A form control instance provides a setValue() method that updates the value of the form control. You can look at https://angular.io/guide/reactive-forms
Upvotes: 1