ng2将formgroup作为参数发送给组件

时间:2017-08-14 12:38:37

标签: angular typescript angular2-template angular2-forms

我有FormGroup包含Sub FormGroup:

weighted = int(number[0])*1 + int(number[1])*2 + int(number[2])*3 + int(number[3])*4

我的主要组件包含abcComponent:

sub formGroup initalize:
    this.fg=new FormGroup({
        name: new FormControl(),
        abcFg: new FormGroup({
            aaa: new FormControl(),
            bbb: new FormControl()
        })
    });

我想将sub formGroup(abc)作为参数(输入)发送到abcComponent。

abcComponent:

@Component({
    selector: 'mainComponent',
    styles: [],
    providers: [],
    template: `
         <div *ngIf="fg">
             <form [formGroup]="fg">
                  <abcComponent></abcComponent>
             </form>
         </div>
         `

我试过了:

@Component({
    selector: 'abcComponent',
    styles: [],
    providers: [],
    template: `
         <div *ngIf="abcFg">
             <form [formGroup]="abcFg">
                 <input type="text" formControlName="aaa" />
                 <input type="text" formControlName="bbb" />
             </form>
         </div>
         `
export class AbcComponent{ 
    @input() public abcFg:FormGroup;
}

但它不起作用......我该如何解决? 谢谢!

1 个答案:

答案 0 :(得分:1)

您可以将abcFg的值传递给abcComponent,如下所示:

<abcComponent [abcFg]="fg.value.abcFg"></abcComponent>

然后在abcComponent

export class AbcComponent implements OnInit{ 
    @input() public abcFg;
    abcfgForm : FormGroup;

    constructor(private fb: FormBuilder){}

    ngOnInit(){
        this.abcfgForm = this.fb.group({
            aaa: [this.abcFg.aaa],
            bbb: [this.abcFg.bbb]
        });
    }
}
相关问题