我有两个用户,我需要从中接受输入并部分保存,在这里,当我在一个子组件中移动任何内容时,两个保存按钮都被启用。 我该如何解决?
子组件
<div [ngModelGroup]="user" #fieldset="ngModelGroup">
<input name="first" [ngModel]="user.first" minlength="2">
<input name="last" [ngModel]="user.last" required>
<button [disabled]="fieldset.pristine||fieldset.invalid">
Save
</button>
</div>
父组件
<form>
<child-component [user]="object1"></child-component>
<child-component [user]="object2"></child-component>
</form>
是否可以为动态引用变量模板
答案 0 :(得分:0)
正在工作的StackBlitz链接:link
注意:感谢 benshabatnoam 的努力。
父组件代码
import { Component, OnInit } from '@angular/core';
@Component({
selector: 'my-app',
templateUrl: './app.component.html',
styleUrls: ['./app.component.css']
})
export class AppComponent implements OnInit {
users = [
{first: 'first user first', last: 'first user last'},
{first: 'second user first', last: 'second user last'}
];
constructor() { }
ngOnInit() {
}
}
父组件HTML
// You don't have to iterate, you can have two or more if you like.
// <child-component [user]="users[0]"></child-component>
// <child-component [user]="users[1]"></child-component>
<ng-container *ngFor="let user of users">
<child-component [user]="user"></child-component>
</ng-container>
儿童组件代码
import { Component, Input } from '@angular/core';
@Component({
selector: 'child-component',
templateUrl: './child.component.html'
})
export class ChildComponent {
@Input() user;
onSubmit(form){
if(form.invalid){
// Do stuff...
}
}
}
儿童组件HTML
<form (ngSubmit)="onSubmit(myForm)" #myForm="ngForm">
<input [(ngModel)]="user.first" name="first" minlength="2">
<input [(ngModel)]="user.last" name="last" required>
<button type="submit" [disabled]="myForm.invalid">
Save
</button>
</form>
答案 1 :(得分:0)
我为每个孩子提供了唯一的“ ngModelGroup”,现在我的问题已解决
Parent.component.html
<form #f="ngForm">
<child-component [formGroupName]="'user1'" [user]="object1"></child-component>
<child-component [formGroupName]="'user2'" [user]="object2"></child-component>
</form>
<pre>{{f.value|json}} </pre>
Child.component.html
<div [ngModelGroup]="formGroupName" #fieldset="ngModelGroup">
<input name="first" [ngModel]="user.first" minlength="2">
<input name="last" [ngModel]="user.last" required>
<button [disabled]="fieldset.pristine||fieldset.invalid">
Save
</button>
</div>
Child.component.ts
import { Component, Input } from '@angular/core';
import { ControlContainer, FormGroup, NgForm } from '@angular/forms';
@Component({
selector: 'child-component',
templateUrl: './child.component.html',
viewProviders: [{provide: ControlContainer, useExisting: NgForm}]
})
export class ChildComponent {
@Input() formGroupName : string;
@Input() user;
}