使用Angular 2,双向绑定在模板驱动的表单中很容易——只需使用香蕉盒语法即可.您将如何以模型驱动的形式复制这种行为?

例如,这是一个标准的react 形式.让我们假设它比看起来复杂得多,有很多很多不同的输入和业务逻辑,因此更适合于模型驱动的方法,而不是模板驱动的方法.

    export class ExampleModel {
        public name: string;
        // ... lots of other inputs
    }

    @Component({
        template: `
            <form [formGroup]="form">
                <input type="text" formControlName="name">
                ... lots of other inputs
            </form>

            <h4>Example values: {{example | json}}</h4>
        `
    })
    export class ExampleComponent {
        public form: FormGroup;
        public example: ExampleModel = new ExampleModel();

        constructor(private _fb: FormBuilder) {
            this.form = this._fb.group({
                name: [ this.example.name, Validators.required ]
                // lots of other inputs
            });
        }

        this.form.valueChanges.subscribe({
            form => {
                console.info('form values', form);
            }
        });
    }

subscribe()中,我可以对表单值应用各种逻辑,并根据需要映射它们.但是,我不想映射表单中的每个输入值.我只想看到整个employee模型更新时的值,方法类似于[(ngModel)]="example.name",并显示在模板的json管道中.我怎样才能做到这一点?

推荐答案

Note:正如@Clouse24,"Using Reactive Froms with ngModel is deprecated in angular 6 and will be removed in a future version of Angular"所提到的(这意味着下面的答案将来将不再受支持).请阅读链接,查看弃用的理由,并了解您将有哪些替代方案.

对于被动形式,您可以使用[(ngModel)].

template

<form [formGroup]="form">
  <input name="first" formControlName="first" [(ngModel)]="example.first"/>
  <input name="last" formControlName="last" [(ngModel)]="example.last"/>
</form>

component

export class App {
  form: FormGroup;
  example = { first: "", last: "" };

  constructor(builder: FormBuilder) {
    this.form = builder.group({
      first: "",
      last: ""
    });
  }
}

Plunker

这将是一个与withoutformControlName完全不同的指令.对于react 形式,它将是FormControlNameDirective.如果没有formControlName,将使用NgModel指令.

Angular相关问答推荐

如何从Angular TS文件传递$Events对象?

导入浏览器模块时出错已导入commonModule的insted,animationBrower也显示错误,当p打开时

自动完成搜索过滤器不适用于Angular 中动态添加的输入字段

仅在从forkJoin获得数据后订阅主题

是否自动处理Angular /RxJS观测数据的取消订阅

带独立零部件的TranslateLoader[Angular 16]

带区域设置用法的Angular 日期管道

NX MFE Angular 模块联合无法访问远程微前端

Storybook 和 Angular 交互游戏测试未定义预期

在 Angular 14 中找不到命名空间google

如何在 Angular 中将tailwind 类传递给 fontawesome

ngx-bootstrap modal:如何从模态中获取返回值?

如何使用 Bootstrap 4 flexbox 填充可用内容?

由router-outlet 创建时如何将css类应用于组件元素?

Angular 5 手动导入语言环境

angular 2 http withCredentials

为什么Angular 12 'ng serve' 构建应用程序的速度很慢?

Angular 2:formGroup 需要一个 FormGroup 实例

Angular 中 polyfills.ts 文件有什么用

如何从materialAngular使用分页器?