在Angular 10中,你可以使用Formly来创建动态表单。当你需要在自定义formly-wrapper中访问字段的值时,可以使用以下解决方法:
import { Component, ViewChild, AfterViewInit } from '@angular/core';
import { FieldWrapper } from '@ngx-formly/core';
@Component({
selector: 'app-custom-wrapper',
template: `
`,
})
export class CustomWrapperComponent extends FieldWrapper implements AfterViewInit {
@ViewChild('fieldComponent', { static: true }) fieldComponent;
ngAfterViewInit() {
// 在视图初始化之后,可以访问字段的值
console.log(this.fieldComponent.field.formControl.value);
}
}
import { Component } from '@angular/core';
import { FormlyFieldConfig } from '@ngx-formly/core';
@Component({
selector: 'app-root',
template: `
`,
})
export class AppComponent {
form = new FormGroup({});
model = {};
fields: FormlyFieldConfig[] = [
{
key: 'name',
type: 'input',
templateOptions: {
label: 'Name',
required: true,
},
wrappers: ['custom-wrapper'],
},
];
onSubmit() {
console.log(this.model);
}
}
import { NgModule } from '@angular/core';
import { FormsModule, ReactiveFormsModule } from '@angular/forms';
import { BrowserModule } from '@angular/platform-browser';
import { FormlyModule } from '@ngx-formly/core';
import { FormlyBootstrapModule } from '@ngx-formly/bootstrap';
import { AppComponent } from './app.component';
import { CustomWrapperComponent } from './custom-wrapper.component';
@NgModule({
declarations: [AppComponent, CustomWrapperComponent],
imports: [
BrowserModule,
FormsModule,
ReactiveFormsModule,
FormlyModule.forRoot(),
FormlyBootstrapModule,
],
bootstrap: [AppComponent],
})
export class AppModule {}
通过以上步骤,你可以在自定义的formly-wrapper组件中访问字段的值。