Reputation: 1078
I am new to Angular and I am working in 8.
I tried the following to disable a submit button. I have one parent component request.html, here I am using the following code,
<div i"parent">
<form #heroForm="ngForm">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" required [(ngModel)]="vname" name="name" #name="ngModel" #spy>
<div [hidden]="name.valid || name.pristine" class="alert alert-danger"> Name is required </div>
<button type="submit" class="btn btn-success" [disabled]="!heroForm.form.valid || spy.className.invalid">Submit</button>
</div>
</form>
</div>
It disbales the submit button as expected, if textbox is empty. This is not a problem
Now I am using other child component inject in request.html, as follows
<form #heroForm="ngForm">
<div id="parent">
<app-child> </app-child>
</div>
<button type="submit" class="btn btn-success"
[disabled]="!heroForm.form.valid || spy.className.invalid">Submit</button>
</form>
and my child html looks like follows,
<div id="child-template">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" required [(ngModel)]="vname" name="name" #name="ngModel" #spy>
<div [hidden]="name.valid || name.pristine" class="alert alert-danger"> Name is required </div>
</div>
</div>
Here My input text box is in child html and I want to disable the save button in parent html, it is not working and the save button always enabled.
Am I missing anything here?
Upvotes: 1
Views: 1390
Reputation: 3387
You can find out complete working StackBlitz Link
You have to emit form status form child to parent using @Output()
and @ViewChild()
decorator.
Your app.component.html is... submitValidator
is just coming from child component.
<div id="parent">
<app-child (submitValidator)="onSubmitValidator($event)"> </app-child>
</div>
Your child.component.ts is ...
here, @ViewChild() is used for getting form status from template, where you have used #name=ngModel
@Output() submitValidator = new EventEmitter();
@ViewChild ('name', {static:false}) formValidator;
ngOnInit() {
this.submitValidator.emit(false);
}
onChange(value){
this.submitValidator.emit(this.formValidator.valid)
}
Your chil.component.html is...
<input type="text" class="form-control" (ngModelChange)="onChange()"
id="name" required [(ngModel)]="vname" name="name"
#name="ngModel" #spy
>
Upvotes: 2
Reputation: 31
Use @Output decorator, which will emit an event to enable/ disable button from child to parent. The event can be called on ngModelChange event of input text box.
Upvotes: 1