Search code examples
angularangular4-forms

Can I autodect a value in an angular directive instead of using a template reference variable?


What I got

I have a directive like this one:

@Directive({
    selector: '[appValidateOnSubmit]'
})
export class ValidateOnSubmitDirective {

    @Input('appValidateOnSubmit')
    set appValidateOnSubmit(form: NgForm) {
        // do something with the form
    }
}

Usage:

<form (ngSubmit)="submit()" [appValidateOnSubmit]="myForm" #myForm="ngForm">
    <!-- ... -->
</form>

This so far works perfectly fine.

Question

Can I somehow eliminate the template reference variable myForm from the HTML? So that I can write simply <form (ngSubmit)="submit()" appValidateOnSubmit> instead of the much longer <form (ngSubmit)="submit()"[appValidateOnSubmit]="myForm" #myForm="ngForm">?

Background is my answer here which I am trying to improve.


Solution

  • Yes there is a way to do that using via @Host

    @Directive({
      selector: '[appValidateOnSubmit]'
    })
    export class ValidateOnSubmitDirective {
    
      constructor(@Host() form: NgForm) {
        console.log(form);
      }
    }