How to add ng-model functionality to a component

后端 未结 2 1322
野趣味
野趣味 2020-12-04 00:48

Angular ng-change on ng-model passed into child directive

Basically, I want to be able to pass in ng-model from a parent directive to a child directive. I could ju

2条回答
  •  醉酒成梦
    2020-12-04 01:47

    How to add ng-model functionality to a component

    Use one-way < input for input and use the ngModelController API for output:

    app.component("checkboxComponent", {
        bindings: { ngModel: '<' },
        require: { ngModelCtrl: 'ngModel' },
        template: `
              
        `,
        controller: function() {
          this.ngModelChange = () => {
            this.ngModelCtrl.$setViewValue(this.ngModel);
          };
        }
    })
    

    The component uses one-way binding for input, and $setViewValue for output. With this method, the ng-change works, and the component can be used as a form element:

    For more information, see

    • AngularJS ngModelController API Reference
    • AngularJS Developer Guide -Implementing custom form controls (using ngModel)

    The DEMO

    angular.module("app",[])
    
    .component("checkboxComponent", {
        bindings: { ngModel: '<' },
        require: { ngModelCtrl: 'ngModel' },
        template: `
            

    Checkbox Component

    Checkbox
    `, controller: function() { this.ngModelChange = () => { this.ngModelCtrl.$setViewValue(this.ngModel); }; } })
    
      
         
        
        

    value = {{value}}

    value2 = {{value2}}

提交回复
热议问题