Angular2 two-way data binding

前端 未结 8 1839
谎友^
谎友^ 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: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).

    
    
    

    You can change the label above by typing something below

提交回复
热议问题