Angular Using ngModel within a form, unnecessary to include one-way or two-way binding

Discussão em 'Angular' iniciado por user1169587, Março 31, 2025.

  1. user1169587

    user1169587 Guest

    In angular documentation https://angular.dev/api/forms/NgModel, it mentions


    In the context of a parent form, it's often unnecessary to include one-way or two-way binding, as the parent form syncs the value for you
    ​

    But I cannot understand why no need to include two-way binding? As this make the form just one way, from ui to ts.

    e.g. https://stackblitz.com/edit/angular-5-starter-app-xzxmc6tp?file=app/app.component.ts,index.html

    <form #f="ngForm" (ngSubmit)="onSubmit(f)" novalidate>
    First Name<input name="first" ngModel required #first="ngModel" />
    Last Name<input name="last" [(ngModel)]='lastName' />
    <button>Submit</button>
    <button type="button" (click)="updateLastName()">Change lastName </button>
    </form>


    in Last Name, I use [(ngModel)]='lastName', then I can modify the lastName property in ts and then shown in UI, if just use ngModel as in first name

    First Name<input name="first" ngModel required #first="ngModel" />


    then I cannot modify the first name in ts and shown in UI (even no a property link to UI First Name textbox).

    So what good to omit [()]? why the document suggest


    In the context of a parent form, it's often unnecessary to include one-way or two-way binding, as the parent form syncs the value for you ?
    ​

    Continue reading...

Compartilhe esta Página