Referencing template items

This is a very noob question, about referencing template items.

Here is the code from one of the articles. My quesiton is, if I make another function, and would like to reference the form(ngForm) in that function, how would I point to it.

 import { Component } from '@angular/core';
@Component({
  template: `
    <form #form="ngForm" (ngSubmit)="logForm(form)" novalidate>
      <ion-item>
        <ion-label>Todo</ion-label>
        <ion-input type="text" required [(ngModel)]="todo.title" ngControl="title"></ion-input>
      </ion-item>
      <ion-item>
        <ion-label>Description</ion-label>
        <ion-textarea [(ngModel)]="todo.description" ngControl="description"></ion-textarea>
      </ion-item>
      <button ion-button type="submit" block>Add Todo</button>
    </form>
  `,
})
export class FormsPage {
  todo = {
    title: '',
    description: ''
  };
  logForm(form) {
    console.log(form.value)
  }
}
1 Like

I know this question is a bit old, but since I was looking for the answer myself, and then found it, I thought Iā€™d answer here.

To access the form from another function you could use ViewChild:

@ViewChild('form') form: NgForm;

So if, for instance, you wanted to prevent them from leaving if the form is dirty, you might do something like this:


import { Component } from '@angular/core';
import { FormBuilder, FormGroup, Validators, NgForm } from '@angular/forms';
@Component({
  template: `
    <form #form="ngForm" (ngSubmit)="logForm(form)" novalidate>
      <ion-item>
        <ion-label>Todo</ion-label>
        <ion-input type="text" required [(ngModel)]="todo.title" ngControl="title"></ion-input>
      </ion-item>
      <ion-item>
        <ion-label>Description</ion-label>
        <ion-textarea [(ngModel)]="todo.description" ngControl="description"></ion-textarea>
      </ion-item>
      <button ion-button type="submit" block>Add Todo</button>
    </form>
  `,
})
export class FormsPage {
  @ViewChild('form') form: NgForm;
  todo = {
    title: '',
    description: ''
  };
  logForm(form) {
    console.log(form.value)
  }
  ionViewCanLeave(): Boolean {
    if (this.form.dirty) {
      /// open a dialog here
      return false;
    } else {
      return true;
    }
  }
}

It seems cleaner to me to use FormBuilder to make a FormGroup in the controller and just access that directly instead of bothering with @ViewChild.