【问题标题】:angular implement my own compoment with ngModelAngular 用 ngModel 实现我自己的组件
【发布时间】:2019-05-16 21:16:54
【问题描述】:

我有以下 HTML,并希望在 inputmy-component 更改时同步 myModel

<input type="text" [(ngModel)]="myModel" />
<my-component [(ngModel)]="myMdoel></my-component>

有什么想法吗?

编辑:

<div *ngFor="let item of items">
    <input type="text" name="item{{item.name}}" [(ngModel)]="item.name" />
    <my-component [(model)]="item.name" [datasource]="source"></my-component>
</div>

我的组件

<button type="button" *ngFor="let s of datasource" (click)="selectItem(s)">{{s}}</button>

export class MyComponent ... {
    _model: any;

    @Input()
    get model(): any {
        return this._model;
    }

    @Input()
    set model(value: any) {
        this._model = vaue;
    }

    @Output() modelChange: EventEmitter<any> = new EventEmitter<any>();

    @Input() datasource: any[];

    ...

    selectItem(item: any): void {
        this._model = item;
        this.modelChange.emit(this._model);
    }
}

【问题讨论】:

  • 你能分享我的组件代码

标签: angular angular-ngmodel ngmodel


【解决方案1】:

你可以只在你的组件上使用一个变量并使用@Input事件发射器,如下所示

<my-component [myModelVar]="myMdoel></my-component>

在你的 my-componnet.ts 中

@input myModelVar;

这里 myModelVar 将在您更新父组件上的 myModel 时进行更改

【讨论】:

  • 如果我更改my-component 中的值怎么办?新值会反映在input 中吗?
  • 你需要实现@output事件发射器并将值传递给父
  • 但是对于每个不同的父母,似乎我必须实现一些东西来接收来自my-component的发射?
  • 是的,否则你可以使用对象并一次性完成
猜你喜欢
  • 1970-01-01
  • 2011-02-28
  • 1970-01-01
  • 2017-07-27
  • 2023-03-03
  • 1970-01-01
  • 2021-12-19
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多