我有一个子组件,其中渲染了文本form input controls
。我的提交按钮在父组件中呈现,因此在提交form
时,我得到的是空data
。
parent-component.html
<form #f="ngForm" name="myForm">
<app-text [users]="users"></app-text>
<br><br>
<button (click)="save(f)">Save</button>
</form>
parent.component.ts
import { Component } from '@angular/core';
import {
NgForm
} from '@angular/forms';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: [ './app.component.css' ]
})
export class ParentComponent {
public users = {
'firstname' :'',
'lastname' :''
};
public constructor()
{
}
save(myForm:NgForm)
{
console.log(myForm.value);
}
}
child.component.ts (TextComponent)
import { Component,Input } from '@angular/core';
@Component({
selector: 'app-text',
templateUrl: './text.component.html',
styleUrls: [ './text.component.css' ]
})
export class TextComponent {
@Input() users:any;
}
child.componet.html
<label>Enter the First Name</label>
<input type="text" [(ngModel)]="users.firstname" name="firstname">
<label>Enter the Last Name</label>
<input type="text" [(ngModel)]="users.lastname" name="lastname">
app.module.ts
import { NgModule,NO_ERRORS_SCHEMA,CUSTOM_ELEMENTS_SCHEMA } from '@angular/core';
import { BrowserModule } from '@angular/platform-browser';
import { FormsModule } from '@angular/forms';
import { AppComponent } from './app.component';
import { TextComponent } from './text/text.component';
@NgModule({
imports: [ BrowserModule, FormsModule ],
declarations: [ AppComponent, TextComponent],
bootstrap: [ AppComponent ],
schemas:[CUSTOM_ELEMENTS_SCHEMA,NO_ERRORS_SCHEMA]
})
export class AppModule { }
这里我要提交带有值的表单,并尝试将数据获取到父组件的save方法中,但是我得到的是空数据。
如何实现?还有其他方法可以实现吗?
请帮助我。谢谢。