【发布时间】:2020-09-12 13:12:11
【问题描述】:
Angular 双向绑定
无论如何我们都可以拥有
[(ngModel)] --> [(propertyName)] 这可能吗 这是面试时问我的???
【问题讨论】:
-
是的,它在某种程度上确实有效,您必须使用
@Input和@Output
Angular 双向绑定
无论如何我们都可以拥有
[(ngModel)] --> [(propertyName)] 这可能吗 这是面试时问我的???
【问题讨论】:
@Input 和 @Output
是的,您可以在很多情况下使用双向绑定。 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 的输出。此命名约定可确保自动绑定它。
【讨论】: