【问题标题】:Angular two way binding [(ngModel)]Angular 双向绑定 [(ngModel)]
【发布时间】:2020-09-12 13:12:11
【问题描述】:

Angular 双向绑定

无论如何我们都可以拥有

[(ngModel)] --> [(propertyName)] 这可能吗 这是面试时问我的???

【问题讨论】:

  • 是的,它在某种程度上确实有效,您必须使用 @Input@Output

标签: angular two-way-binding


【解决方案1】:

是的,您可以在很多情况下使用双向绑定。 official docs中有很多例子。

如果您有一个带有@Input@Output 的组件,您可以使用它。

如果这是您的组件:

src/app/sizer.component.ts

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

@Component({
  selector: 'app-sizer',
  templateUrl: './sizer.component.html',
  styleUrls: ['./sizer.component.css']
})
export class SizerComponent {


  @Input()  size: number | string;
  @Output() sizeChange = new EventEmitter<number>();

  dec() { this.resize(-1); }
  inc() { this.resize(+1); }

  resize(delta: number) {
    this.size = Math.min(40, Math.max(8, +this.size + delta));
    this.sizeChange.emit(this.size);
  }

}

src/app/sizer.component.html

<div>
  <button (click)="dec()" title="smaller">-</button>
  <button (click)="inc()" title="bigger">+</button>
  <label [style.font-size.px]="size">FontSize: {{size}}px</label>
</div>

您可以按如下方式使用它:

<app-sizer [(size)]="fontSizePx"></app-sizer>
<div [style.font-size.px]="fontSizePx">Resizable Text</div>

这里的秘密在于假设您希望对大小进行两种方式绑定。所以应该有一个名称为 size 的输入和一个名称为 sizeChange 的输出。此命名约定可确保自动绑定它。

【讨论】:

  • 输出属性名应该是@Output() sizeChange = new EventEmitter();大小合适???
  • 如果输入名称是大小。是的,双向绑定必须具有名称 sizeChange。
猜你喜欢
  • 2017-04-29
  • 2017-08-28
  • 2019-01-02
  • 2016-10-12
  • 1970-01-01
  • 2017-10-20
  • 2015-10-15
相关资源
最近更新 更多