如何在Angular 6中使用ngModel创建自定义输入组件? [英] How to create custom input component with ngModel working in angular 6?

查看:452
本文介绍了如何在Angular 6中使用ngModel创建自定义输入组件?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

由于我使用具有很多相同指令的输入,并且应用了.css类,因此我想将重复的代码提取到某些组件中,如下所示:

Since I use inputs with a lot of the same directives and .css classes applyed, I want to extract the repeated code to some component like this:

  @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一起用作普通输入:

The problem here is creating a component in such a way that it can be used with ngModel as an ordinary input:

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

我已经在互联网上找到了一些可以部分或完全过时的解决方案,例如: Angular 2自定义表单输入 可以在角度6中更好地做到这一点吗?

I've found several solutions on the internet that can be partially or completely outdated now like: Angular 2 custom form input Can this be done in a better way in angular 6?

推荐答案

这也可以这样做,当您创建双向绑定[()]时,可以使用相同的名称+'change将其绑定到函数'(在我们的示例中为inputModel和inputModelChange),当您触发inputModelChange.emit('updatedValue')时,ngModel将更新.并且只需在组件内部声明一次即可.

this can also be done like this, when you create a two way binding [()] you can bind it to a function using the same name + 'change' (in our case inputModel and inputModelChange) this way the ngModel will update when you trigger inputModelChange.emit('updatedValue'). and you only need to declare it once inside your component.

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 6中使用ngModel创建自定义输入组件?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆