Search code examples
angulardata-bindingangular-materialangular18

angular 18 two way data binding


Can't bind to 'ngModel' since it isn't a known property of 'textarea' component.html

<textarea rows="6" [(ngModel)]="enteredValue"></textarea>
<button (click)="onSavePost()">save</button>
<p>{{ newPost }}</p>

component.ts

import { Component } from '@angular/core';
@Component({
  selector: 'app-post-create',
  standalone: true,
  templateUrl: './post-create.component.html',
  styleUrl: './post-create.component.css'
})
export class PostCreateComponent {
newPost="NO content Here";
enteredValue='';
onSavePost(){
  this.newPost = this.enteredValue;
}
}

app.component.ts

import { Component } from '@angular/core';
import { RouterOutlet } from '@angular/router';
import { PostCreateComponent } from './post/post-create/post-create.component';
import { FormsModule } from '@angular/forms';
@Component({
  selector: 'app-root',
  standalone: true,
  imports: [RouterOutlet,FormsModule,PostCreateComponent],
  templateUrl: './app.component.html',
  styleUrl: './app.component.css'
})
export class AppComponent {
  title = 'Project_ng_demo';
}

here is not app.module.ts file in agnular 18

import FormsModule in app.component.ts. import { FormsModule } from '@angular/forms';


Solution

  • Issue is that when using standalone components, children components do not automatically get imports from parents thus PostCreateComponent needs to import the FormsModule as well.

    import { Component } from '@angular/core';
    import { FormsModule } from '@angular/forms';
    
    @Component({
      selector: 'app-post-create',
      standalone: true,
      imports: [FormsModule],
      templateUrl: './post-create.component.html',
      styleUrl: './post-create.component.css'
    })
    export class PostCreateComponent {
    newPost="NO content Here";
    enteredValue='';
    onSavePost(){
      this.newPost = this.enteredValue;
    }
    }