import { Component, OnInit, Input, HostBinding, Output, EventEmitter, AfterViewChecked, ChangeDetectorRef, OnChanges, SimpleChanges, DoCheck } from '@angular/core'; import { IDynamicBaseControl } from './interfaces/dynamic-control.interface'; import { FormGroup, FormBuilder } from '@angular/forms'; import { DynamicControlGroupService } from './services/dynamic-control-group.service'; @Component({ selector: 'farris-dynamic-control-group', template: `
`, providers: [ DynamicControlGroupService ] }) export class DynamicControlGroupComponent implements OnInit, OnChanges, AfterViewChecked { @HostBinding('class') className: string; @Input() contents: Array; @Input() form: FormGroup = null; @Input() extraClassNames: string; @Input() isControlInline: boolean = true; @Input() isEmbedded: boolean = false; private _formData; @Input() set formData(value:any){ if(value){ this._formData=value; if(this.form){ this.form.patchValue(this.controlGroupService.toFormValue(this.contents, this._formData)); } } } get formData(){ return this._formData; } @Input() uri: string; @Input() isGrouped: boolean; controlEntries: Array>; constructor(private controlGroupService: DynamicControlGroupService, private cdRef: ChangeDetectorRef) { } ngOnChanges(changes: SimpleChanges): void { this.className = this.initStyles(); if(this.isGrouped && this.contents){ this.controlEntries = Array.from(this.groupControls(this.contents).entries()); } } ngOnInit() { //使用模态框动态加载本组件时,拿到了本组件的实例,同时初始赋值,会在此第一次拿到@input初始值 this.className = this.initStyles(); if(this.contents && this.contents.length){ this.initFormAndControlEntries(); }else{ this.uri && this.controlGroupService.getFormControlsByUri(this.uri).subscribe(data => { this.contents = data; this.initFormAndControlEntries(); }); } } initFormAndControlEntries(){ // this.form = this.controlGroupService.toFormGroup(this.contents, this.form); if(this.isGrouped){ this.controlEntries = Array.from(this.groupControls(this.contents).entries()); } if(this.formData===undefined){return;} this.form.patchValue(this.controlGroupService.toFormValue(this.contents, this.formData)); } groupControls(contents: Array): Map> { const groupedControls = new Map>(); contents.forEach(control => { if(groupedControls.has(control.groupName)){ groupedControls.get(control.groupName).push(control); }else{ groupedControls.set(control.groupName, [control]); } }); return groupedControls; } initStyles(): string{ let styleClass: string; styleClass = this.isGrouped ? "f-form-layout" : "f-utils-flex-row-wrap"; styleClass = this.extraClassNames ? styleClass.concat(` ${this.extraClassNames}`) : styleClass; styleClass = this.isEmbedded ? styleClass : styleClass.concat(" farris-form"); styleClass = this.isControlInline ? styleClass.concat(" farris-form-controls-inline") : styleClass; return styleClass; } ngAfterViewChecked() { // this.cdRef.detectChanges(); } }