Imagine a scenario where you have a simple HTML form with two input fields in a component of an Angular 4 application. The first input field is directly implemented, while the second one is within a child component:
<form #personForm="ngForm">
<input type="text" required name="firstname [(ngModel)]="firstname"/>
<app-smart-input required [(model)]="lastname"></app-smart-input>
<button [disabled]="personForm.valid === false">Send</button>
</form>
The child component's code looks like this:
import { Component, EventEmitter, Input, OnInit, Output } from "@angular/core";
@Component({
selector: "app-smart-input",
templateUrl: "./smart-input.component.html",
styleUrls: ["./smart-input.component.css"]
})
export class SmartInputComponent {
////////////////
// PROPERTIES //
////////////////
@Input() model: string;
@Output() modelChange: EventEmitter<string> = new EventEmitter<string>();
@Input("required") required: boolean = false;
/////////////
// METHODS //
/////////////
updateChanges() {
this.modelChange.emit(this.model);
}
}
The HTML template for the child component is as follows:
<input type="text" [required]="required" [(ngModel)]="model" (ngModelChange)="updateChanges()" />
At this point, updating the models works flawlessly – both firstname
and lastname
are correctly defined based on user input.
However, the goal now is to disable the button on the form unless both fields are filled out. The required
attribute is used in the <input>
implementations to ensure that values are not null or undefined.
Unfortunately, the button is currently only disabled if the firstname
field is empty or invalid, disregarding the validation status of the lastname
. How can this be addressed?
Please note that while Angular 2 creating reactive forms with nested components may provide some insights, the approach here involves using a template-driven form rather than a reactive form. Nonetheless, there may be ways to adapt the concepts.