Angular 2 Template Driven Form access ngForm in component

后端 未结 2 1753
感情败类
感情败类 2020-12-09 01:53

I want to use template driven forms in Angular 2 and I need to access the current ngForm in my directive, as local property and I don\'t want to pass them as parameter.

相关标签:
2条回答
  • 2020-12-09 02:30

    You need the ngControl attribute on the inputs you want to check.

    <form #frm="ngForm" (ngSubmit)="save(frm)">
       <input [(ngModel)]="user.name" #name="ngForm" ngControl="name"  type="text">
       <a (click)="showFrm()">Show Frm</a>
    </form>
    

    and in the component you can access the "frm" variable with

    import {Component, ViewChild} from 'angular2/core';
    ...
    @ViewChild('frm') public userFrm: NgForm;
    ...
    public showFrm(): void{
        console.log(this.frm);
    }
    

    You can't access the frm in the constructor, it's not there at this moment, but in the ngAfterViewInit you can access it.

    since Angular 8 or so they have updated the parameters for ViewChild. Currently I need to use this syntax:

    @ViewChild('frm', { static: true })userFrm: NgForm;
    
    0 讨论(0)
  • 2020-12-09 02:31
    <h1>Login</h1>
    <hr />
    <div class="col-md-4">
      <form autocomplete="off" #loginForm="ngForm" (ngSubmit)="login(loginForm.value)">
        <div class="form-group">
          <em *ngIf="loginForm.controls.userName?.invalid">required</em>
          <label for="userName">User Name:</label>
          <input
            id="userName"
            (ngModel)="(userName)"
            name="userName"
            type="text"
            class="form-control"
            placeholder="User Name..."
          />
        </div>
        <div class="form-group">
          <em *ngIf="loginForm.controls.password?.invalid">required</em>
          <label for="password">Password:</label>
          <input
            id="password"
            (ngModel)="(password)"
            name="password"
            type="password"
            class="form-control"
            placeholder="Password..."
          />
        </div>
    
        <button type="submit" [disabled="loginForm.invalid" ]class="btn btn-primary">Login</button>
        <button type="button" class="btn btn-default">Cancel</button>
      </form>
    </div>
    
    import { Component } from '@angular/core';
    import { AuthService } from './auth.service';
    
    @Component({
      selector: 'login',
      templateUrl: './app/login/login.component.html'
    })
    export class LoginComponent {
      constructor(private authService: AuthService) {}
    
      login(formValues) {
        this.authService.loginUser(formValues.userName, formValues.password);
      }
    }
    
    0 讨论(0)
提交回复
热议问题