因为我使用的输入有很多相同的指令和.应用css类,我想将重复代码提取到如下组件:

  @Component({
  selector: "app-input",
  template: `
    <div class="...">
      <input type="..." name="..." class="..." [(ngModel)]="value" someDirectives...>
      <label for="...">...</label>
    </div>
  `,
  ...
  })
  export class InputComponent implements OnInit {
    // some implementation connecting external ngModel with internal "value" one
  }

这里的问题是,创建一个组件时,它可以与ngModel一起用作普通输入:

<app-input [(ngModel)]="externalValue" ... ></app-input>

我在互联网上找到了几种可能部分或完全过时的解决方案,比如:

推荐答案

这也可以这样做,当你创建一个双向绑定[()]时,你可以使用相同的名称+change(在我们的例子中是inputModel和inputModelChange)将它绑定到一个函数,这样当你触发inputModelChange时,ngModel就会更新.emit('updatedValue').只需在组件中声明一次.

app-input.component.ts

import { Component, OnInit, Output, Input, EventEmitter } from '@angular/core';

@Component({
  selector: 'app-input',
  template: `  <input type="text" [(ngModel)]="inputModel" (ngModelChange)="inputModelChange.emit(inputModel)"/>`,
  styleUrls: ['./app-input.component.scss']
})
export class AppInputComponent {
  @Input() inputModel: string;
  @Output() inputModelChange = new EventEmitter<string>();
}

app.component.html

<app-input [(inputModel)]="externalValue"></app-input>

Angular相关问答推荐

AG网格Angular 快捷菜单调用函数

在Angular 应用中混合使用较少和较粗俗的文件

PrimeNg选项卡视图选项卡

如何从URL中角下载图片?

VS代码中带Angular 17的缩进新控制流

如何在 Angular RxJS 中替换订阅中的 subscrib?

为什么Angular的ViewEncapsulation枚举有没有值为1的键?

等待两个订阅完成而不嵌套

Angular:为什么在我的自定义 ErrorHandler 中订阅主题不触发?

Angular:将间隔与增量和减量相结合

从 angular 11 升级到 angular 12 后,我的项目没有使用优化参数进行编译

如何从表单组中禁用的表单控件中获取值?

如何在 Angular 2 模板中使用枚举

如何将新的 FormGroup 或 FormControl 添加到表单

Angular CLI 自定义 webpack 配置

如何手动延迟加载模块?

unexpected token < 错误

在Angular 6 中找不到 HammerJS

Angular2 Routerlink:添加查询参数

Angular 2 中的动态模板 URL