Angular2 two-way data binding

前端 未结 8 1809
谎友^
谎友^ 2020-12-15 05:10

I know Angular2 doesn\'t have two-way data binding but is there a way to mimick the two-way data binding behavior from Angular1.x?

相关标签:
8条回答
  • 2020-12-15 05:41

    From the Docs:

    Two-way binding ( [(...)] )

    You often want to both display a data property and update that property when the user makes changes.

    On the element side that takes a combination of setting a specific element property and listening for an element change event.

    Angular offers a special two-way data binding syntax for this purpose, [(x)]. The [(x)] syntax combines the brackets of property binding, [x], with the parentheses of event binding, (x).

    [( )] = BANANA IN A BOX
    

    Visualize a banana in a box to remember that the parentheses go inside the brackets.

    For more information, see

    • Angular Developer Guide - Template Syntax - Two-way binding
    • Angular @angular/forms API Reference - ngModel Directive
    0 讨论(0)
  • 2020-12-15 05:46

    You can do this by attaching to the events on the input field and updating the internal value as is done in this example:

    http://plnkr.co/edit/lOFzuWtUMq1hCnrm9tGA?p=preview

    Create a component that has an internal attribute that holds the label this.label and a callback changeLabel that expects an event object

    @Component({
      selector: 'app',
      templateUrl: 'bound.html'
    })
    class App {
      label: string;
      constructor() {
        this.label = 'default label'
      }
      changeLabel(event) {
        this.label = event.target.value;
      }
    }
    
    bootstrap(App);
    

    The create your template and attach the callback to the appropriate event (you could attach it to the keypress event but then you might need a timeout. I attached it to the change event for simplicity (which means you might need to tab off the input to see the update).

    <label for="myinput">{{label}}</label>
    <input id="myinput" type="text"/>
    <p></p>You can change the label above by typing something below</p>
    <label for="labeltext">New Label Text</label>
    <input type="text" id="labeltext" (change)="changeLabel($event)"/>
    
    0 讨论(0)
提交回复
热议问题