#Correct handling of ViewChild property decorator

3 messages · Page 1 of 1 (latest)

upper walrus
#

I am accustomed to using the view child for certain cases where I want to handle DOM elements, for example when someone presses a submit button I disable it and also the cancel button or any other button that needs to apply the same thing.

To do this, I do something like this:

@ViewChild('submitButton') submitButton!: ElementRef<HTMLInputElement>;
@ViewChild('cancelButton') cancelButton!: ElementRef<HTMLInputElement>;

First I assign the view child to the DOM elements.

Second, when the function is called, I access its native element:

submit() {
  this.submitButton.nativeElement.disabled = true:
  this.cancelButton.nativeElement.disabled = true:
}
ebon herald
#
@Component({
  template: `
<form [formGroup]="theForm" (ngSubmit)="onSubmit()">
  <button [disabled]="theForm.invalid || isSubmitting" type="submit">Submit</button>
  <button (click)="onCancel()" [disabled]="isSubmitting" type="button">Cancel</button>
</form>
`,
})
export class TheFormComponent {
  public isSubmitting = false;
  public readonly theForm: FormGroup;

  constructor(private readonly service: TheService) {
    this.theForm = new FormGroup({});
  }

  public onSubmit(): void {
    this.isSubmitting = true;
  }
}
#

That said, I'm not sure why you would do disabling instead of debounceing with Observables in submitting. Show more code for better advice