Angular 2 自定義 雙向綁定 屬性

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

@Component({
    selector: 'twoway',
    template: `
       <input [(ngModel)]="username">
       <p>Hello {{username}}!</p>
    `
})
export class TwoWayComponent implements OnInit {
    constructor() { }

    usernameValue: string;
    @Output() usernameChange = new EventEmitter();

    @Input()
    get username() {
        return this.usernameValue;
    }
    set username(val) {
        this.usernameValue = val;
        this.usernameChange.emit(this.usernameValue);
    }

    ngOnInit() {

    }
}

使用時,就能夠經過[(username)]=「你的當前屬性」 進行雙向綁定了。屬性名 + 後綴 Change是一個約定的固定寫法。this

相關文章
相關標籤/搜索