0

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.

yankee
  • 38,872
  • 15
  • 103
  • 162

1 Answers1

3

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

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

  constructor(@Host() form: NgForm) {
    console.log(form);
  }
}
penleychan
  • 5,370
  • 1
  • 17
  • 28