大家好,我是第一个使用angular 5
的项目我正在处理表单,以便在其下创建多个检察官的问题 所以我在CreateIssueComponent上制作了一般信息 和ProsecutorsComponent
上的检察官(应该是输入数组)数据第一: 我想在CreateIssueComponent上提交表单时获取ProsecutorsComponent的输入值? 第二: 我想知道为什么要把检察官作为一系列的输入,以及像
这样的回报检[1] [名称]
检[1] [电子邮件]
检[2] [姓名]
检[2] [电子邮件]
ProsecutorsComponent(孩子)
import { Component, OnInit, Input } from '@angular/core';
@Component({
selector: 'app-prosecutors',
templateUrl: './prosecutors.component.html',
styleUrls: ['./prosecutors.component.css']
})
export class ProsecutorsComponent implements OnInit {
@Input() index : number;
constructor() { }
ngOnInit() {
}
}
CreateIssueComponent(parent)
import { Component, OnInit, ViewChild, ViewEncapsulation } from '@angular/core';
import { NgForm } from '@angular/forms';
import { Response } from '@angular/http';
@Component({
selector: 'app-create-issue',
templateUrl: './create-issue.component.html',
styleUrls: ['./create-issue.component.css'],
encapsulation: ViewEncapsulation.None
})
export class CreateIssueComponent implements OnInit {
@ViewChild('f') issueInsert: NgForm;
prosecutorsNoArray : number[] = [1];
prosecutorsNoBinding : number = 1;
constructor() {
}
ngOnInit() {
}
insertIssue(){
console.log(this.issueInsert.value);
}
onchangeProsecutorsNo(){
this.prosecutorsNoArray = Array(this.prosecutorsNoBinding).fill(1);
}
}
create-issue.component.html(parent)
<form (ngSubmit)="insertIssue()" #f="ngForm">
<div>
<div>
issue Name
<input class="form-control m-input" type="number" name="Name" ngModel #Name="ngModel" required>
</div>
<div>
Prosecutors No
<input class="form-control m-input" type="number" [(ngModel)]="prosecutorsNoBinding" (change)="onchangeProsecutorsNo()" name="prosecutorsNo" ngModel #prosecutorsNo="ngModel" required>
</div>
<h3 class="parties">Prosecutors</h3>
<app-prosecutors *ngFor="let prosecutor of prosecutorsNoArray; let i = index" [index]="i"></app-prosecutors>
</form>
prosecutors.component.html(孩子)
<div>
Prosecutors name
<input class="form-control m-input" type="text" name="name_{{ index }}" ngModel #name="ngModel" required>
</div>
我试图删除任何无用的代码,以便尽可能清楚地说明
问候
答案 0 :(得分:2)
对于您的第一个问题,您可以按照示例使用EventEmitter:
import { Component, Output, EventEmitter } from '@angular/core';
@Component({
selector: 'user-profile',
template: '<div>Hi, my name is {{user.name}}</div>'
})
export class UserProfile {
@Output() userUpdated = new EventEmitter();
constructor() { // this can be any method that you want
// Update user
// ...
this.userUpdated.emit(this.user);
}
}
现在,当我们在其父组件中使用此组件时,我们可以绑定用户配置文件发出的事件
template:
`...
<user-profile (userUpdated)="handleUserUpdated($event)"></user-profile>
...`
export class SettingsPage {
constructor(){}
handleUserUpdated(user) {
// here *user* is equal to emitted value in *UserProfile*
}
}
对于你的第二个问题,你可以这样做:
prosecutor: {
name: string,
email: string
};
prosecutors = [];
_method() {
this.prosecutor.name = 'test';
this.prosecutor.email = 'test@test.com';
this.prosecutors.push(this.prosecutor);
...
}
我希望它可以帮助你评论是否有任何问题