如何使用角度4中的ngModel从表单中获取值

时间:2017-09-22 05:19:07

标签: javascript angular

我在输入框中使用ngModel时出现此错误。 的 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>

这是details.components.html文件和 最后一个是details.components.ts文件。

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

2 个答案:

答案 0 :(得分:1)

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

答案 1 :(得分:0)

似乎你是以错误的方式获取输入。尝试获取这样的输入:

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

  constructor() {
  }

  ngOnInit() {
  }
}

您还必须从'@ angular / core'导入'Input'模块,如下所示:

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