Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
307 views
in Technique[技术] by (71.8m points)

Angular 2 Template Driven Form access ngForm in component

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.

my form looks like this:

<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>

and in my component

@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);
    }
}

Is this possible, because I need to check if the myFrm ist valide or was touched in a function where I can't pass the current form as parameter e.g. "routerCanDeactivate" and I don't want to use model driven forms its way too much to write in code and I love the old school ng1 model binding.

I've updated my Example and the frm is not known in the component.

question from:https://stackoverflow.com/questions/37093432/angular-2-template-driven-form-access-ngform-in-component

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...