I've created a form with a selection of packages above the form. The form includes a package input which is readonly. My intention is to change its value via property binding according to what package the user has selected. The property selectedPackage (which I already created) shall be displayed in the input field and updated.
I've had the same problem before with a template driven form. I this case the solution was to use [(ngModel)]="selectedPackage".
HTML:
<form class="w-50 mb-5 mt-5" [formGroup]="contactForm" (ngSubmit)="onSubmit()">
<div class="form-group">
<div class="form-row">
<div class="col">
<input type="text" name="name" id="name" class="form-control" placeholder="Name" formControlName="name">
</div>
<div class="col">
<input type="text" name="lastname" id="lastname" class="form-control" placeholder="Future Family Name" formControlName="lastname">
</div>
</div>
</div>
<div class="form-group">
<input type="email" name="email" id="email" class="form-control" placeholder="E-Mail" formControlName="email">
</div>
<div class="form-group">
<input type="text" name="package" id="package" placeholder="Please choose a package from the selection above!" class="form-control" formControlName="package" readonly>
</div>
<div class="form-group">
<input type="date" name="date" id="date" class="form-control" formControlName="date">
</div>
<div class="form-group">
<textarea class="form-control" name="text" id="text" rows="4" placeholder="Your message.." formControlName="text"></textarea>
</div>
<div class="w-100 d-flex justify-content-center">
<div class="row">
<div class="col-12 text-center">
<span class="alert-info-display-none">Please fill in the required fields above.</span>
</div>
<div class="col-12 text-center mt-2">
<button type="submit">Send</button>
</div>
</div>
</div>
</form>
Typescript:
@Input() selectedDiv: number;
selectedPackage: string;
contactForm: FormGroup;
onSubmit(): void {
console.log(this.contactForm);
}
changePackageInfo(): void {
if (this.selectedDiv === 0) {
this.selectedPackage = '';
}
if (this.selectedDiv === 1) {
this.selectedPackage = 'You\'ve chosen Package One';
}
if (this.selectedDiv === 2) {
this.selectedPackage = 'You\'ve chosen Package Two';
}
if (this.selectedDiv === 3) {
this.selectedPackage = 'You\'ve chosen Package Three';
}
}
public ngOnChanges(changes) {
if ('selectedDiv' in changes) {
this.changePackageInfo();
}
}
constructor() { }
ngOnInit() {
this.changePackageInfo();
this.contactForm = new FormGroup({
name: new FormControl(null),
lastname: new FormControl(null),
email: new FormControl(null),
package: new FormControl(null),
date: new FormControl(null),
text: new FormControl(null),
});
}