skip to Main Content

I’m trying to detect changes in my template-driven form but It throws an error because of NgModel is not using the standalone property.

when adding it neglects the value changes

        this.ngForm.form.valueChanges.subscribe((x) => {
      debugger
            if (
                x.selectedProject &&
                x.selectedProject !== this.wizardService.selectedProject
            ) {
                debugger;
                console.log(true);
            }
        })
    ```

it is not going throw the function above but when removing the standalone flag it works but I get the Ngmodel form error

2

Answers


  1. Try this one:

    <form>
      <input
        type="text"
        [(ngModel)]="selectedProject"
        ngModelOptions="{ standalone: true }"
        #selectedProjectInput="ngModel"
      />
    </form>
    
    import { Component, OnInit } from '@angular/core';
    import { FormControl } from '@angular/forms';
    
    @Component({
      selector: 'my-app',
      templateUrl: './app.component.html',
      styleUrls: ['./app.component.css'],
    })
    export class AppComponent implements OnInit {
      selectedProject = new FormControl('');
    
      constructor() {}
    
      ngOnInit() {
        this.selectedProject.valueChanges.subscribe((x) => {
          console.log(x);
        });
      }
    }
    
    Login or Signup to reply.
  2. In a template drive form you need give "name" to your input, e.g.

    <input name="id" [(ngModel)]="variable">
    

    Has no related with [ngModelOptions]={standalone:true} (see that it’s between [ ]. This attribute is used when you have inside a formGroup.

    BTW,we can control when change in several ways

    1. Split ngModel

      <input name="id" [ngModel]="variable" 
                       (ngModelChange)="variable=$event;doSomething($event)">
      
    2. Getting with a ViewChild and subscribe to control.valueChanges

        <input name="id"
          type="text"
          [(ngModel)]="name"
          #nameInput="ngModel"
        />
        @ViewChild('nameInput',{static:true}) control!:NgModel
        ngOnInit(){
          this.control.control.valueChanges.subscribe(res=>{
            console.log(res)
          })
        }
      
    3. using the event input

      <input name="id" [(ngModel)]="variable" 
         (input)="doSomething($event.target.value)">
      
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search