When using template driven forms in Angular 2, how to access the form in the component?

yotube
0

Issue

I have a simple template driven form like so:

HTML:

<div class="container">
<h1>Hero Form</h1>

<form (ngSubmit)="onSubmit()" #heroForm="ngForm">
<div class="form-group">
<label for="name">Name</label>
<input type="text" class="form-control" id="name" [(ngModel)]="model.name" name="name" #name="ngModel">
</div>

<div class="form-group">
<label for="alterEgo">Alter Ego</label>
<input type="text" class="form-control" id="alterEgo" [(ngModel)]="model.alterEgo" name="alterEgo">
</div>

<div class="form-group">
<label for="power">Hero Power</label>
<select class="form-control" id="power" [(ngModel)]="model.power" name="power">
<option *ngFor="let pow of powers" [value]="pow">{{pow}}</option>
</select>
</div>

<button type="submit" class="btn btn-success" [disabled]="!heroForm.form.valid">Submit</button>
</form>
</div>

Component:

import { Component, OnInit } from '@angular/core';
import { Hero } from './hero';

@Component({
selector: 'at-hero',
templateUrl: './hero.component.html',
styleUrls: ['./hero.component.scss']
})

export class HeroComponent implements OnInit {
constructor() {
//
}

ngOnInit() {
//
}

powers = ['Really Smart', 'Super Flexible', 'Super Hot', 'Weather Changer'];

model = new Hero(18, 'Dr IQ', this.powers[0], 'Chuck Overstreet');

submitted = false;

onSubmit() { this.submitted = true; }

newHero() {
this.model = new Hero(42, '', '');
}
}

How can I:

  1. Reset the whole form from the component (not from the markup)?
  2. Reset a single form field (e.g. the name field) also from the component and not the markup?

Solution

You can get the form by using ViewChild

Markup

<form (ngSubmit)="onSubmit()" #heroForm="ngForm">
...
</form>

Component

@ViewChild('heroForm') public heroForm: NgForm;

I suggest you also to look at Reactive Forms too. I think this will be more handy if you want to work with form in the typescript, not in the markup



Answered By - Suren Srapyan

Post a Comment

0Comments
Post a Comment (0)

#buttons=(Accept !) #days=(20)

Our website uses cookies to enhance your experience. Learn More
Accept !
To Top