Pradip Dhakal
Pradip Dhakal

Reputation: 1962

How to get values from form using ngModel in angular 4

I have this error when i use ngModel in input boxes. In .html page

    <form>
    <div *ngIf="editTitle" class="form-group">
        <input type="input" class="form-control" name="title" required 
        placeholder="title" [(ngModel)]="video.title">
    </div>
        <h3 *ngIf="!editTitle" (click)="onTitleClick()">{{video.title}}</h3>
    </form>

This is the details.components.html file and the last one is the details.components.ts file.

In .ts page

import { Component, OnInit } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';

@Component({
selector: 'video-detail',
templateUrl: './video-detail.component.html',
styleUrls: ['./video-detail.component.css'],
inputs: ['video']
})
export class VideoDetailComponent implements OnInit {

private editTitle: boolean = false;
constructor() { }
ngOnInit() {
}

ngOnChanges(){
this.editTitle = false;
}

onTitleClick(){
this.editTitle = true;
}
}

Upvotes: 1

Views: 2206

Answers (2)

Ravi Teja
Ravi Teja

Reputation: 659

app.component.html

<form><div *ngIf="editTitle" class="form-group">
  <input type="input" class="form-control" name="title" required 
  placeholder="title" [(ngModel)]="video.title"></div>
  <h3 *ngIf="!editTitle" (click)="onTitleClick()">{{video.title}}</h3>
  </form>

app.module.ts

import { BrowserModule } from '@angular/platform-browser';
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { AppComponent } from './app.component';

@NgModule({
declarations: [
 AppComponent
 ],
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule
],
providers: [],
bootstrap: [AppComponent]
})
export class AppModule { }

app.component.ts

import { Component, OnInit } from '@angular/core';
@Component({
selector: 'app-root',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
video: any = {};
private editTitle: boolean = false;
constructor() { }
ngOnInit() { }
ngOnChanges(){
this.editTitle = false;
}
onTitleClick(){
this.editTitle = true;
}
}

Upvotes: 2

Rohit Goyal
Rohit Goyal

Reputation: 222

Seems are you are getting the input in a wrong way.Try getting the input like this:

export class VideoDetailComponent implements OnInit {
  @Input() video:object;

  constructor() {
  }

  ngOnInit() {
  }
}

You also have to import the 'Input' module from '@angular/core' like below:

import { Component, OnInit,Input } from '@angular/core';

Upvotes: 0

Related Questions