[英]Angular two way binding [(ngModel)]
Angular 雙向綁定
無論如何我們都可以擁有
[(ngModel)] --> [(propertyName)] 這可能在面試中問過我嗎???
是的,您可以在許多情況下使用雙向綁定。 官方文檔中有很多例子。
如果您有一個帶有@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。 此命名約定確保自動綁定它。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.