[英]When using template driven forms in Angular 2, how to access the form in the component?
[英]Angular 2 Template Driven Form access ngForm in component
我想在 Angular 2 中使用模板驅動的表單,我需要在我的指令中訪問當前的 ngForm,作為本地屬性,我不想將它們作為參數傳遞。
我的表格是這樣的:
<form #frm="ngForm" (ngSubmit)="save(frm)">
<input [(ngModel)]="user.name" #name="ngForm" type="text">
<a (click)="showFrm()" class="btn btn-default">Show Frm</a>
</form>
在我的組件中
@Component({
selector: 'addUser',
templateUrl: `Templates/AddUser`,
})
export class AddUserComponent implements CanDeactivate {
public user: User;
// how can I use this without defining the whole form
// in my component I only want to use ngModel
public frm : ngForm | ControlGroup;
public showFrm() : void{
//logs undefined on the console
console.log(this.frm);
}
}
這可能嗎,因為我需要檢查 myFrm ist 是否有效或在我無法將當前表單作為參數傳遞的函數中被觸及,例如“routerCanDeactivate”,我不想過多地使用模型驅動的表單用代碼編寫,我喜歡老式的 ng1 模型綁定。
我已經更新了我的示例,但 frm 在組件中是未知的。
您需要在要檢查的輸入上使用ngControl
屬性。
<form #frm="ngForm" (ngSubmit)="save(frm)">
<input [(ngModel)]="user.name" #name="ngForm" ngControl="name" type="text">
<a (click)="showFrm()">Show Frm</a>
</form>
在組件中,您可以訪問“frm”變量
import {Component, ViewChild} from 'angular2/core';
...
@ViewChild('frm') public userFrm: NgForm;
...
public showFrm(): void{
console.log(this.userFrm);
}
您無法在構造函數中訪問frm
,此時它不存在,但在 ngAfterViewInit 中您可以訪問它。
從 Angular 8 左右開始,他們更新了 ViewChild 的參數。 目前我需要使用這種語法:
@ViewChild('frm', { static: true })userFrm: NgForm;
<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);
}
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.